Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP public function behaves like static

I was reading a book about PHP when I ran into a strange part of code:

 class Employee {
        public function show() {
            echo "show launched\n";
        }
    }

    Employee::show();

I came from C++ so I was going to bet this code wouldn't work. This is why I tested it.

And it worked, showing "show launched" (omg, am I drunk?)!

It seems to be breaking the concept that method of class can be called without instantiation of class.

  • What is the point then of static identifier in classes?
  • Are all public functions static too? Really, what am I missing?

Thanks in advance.


Addition: Just a notice.

I found that in this book. Pages 178-179 and it's given as correct example (if I'm right)

like image 399
Tebe Avatar asked Dec 11 '22 07:12

Tebe


1 Answers

Yeah that would work but with a warning. You may have turned off your error reporting on PHP by the way...

Strict standards: Non-static method Employee::show() should not be called statically

Adding a static keyword before the function definition would make the warning dissappear.

Below code works without a warning..

<?php
class Employee {
    public static function show() { //<----- Added the static keyword.
        echo "show launched\n";
    }
}

Employee::show();

To answer your question...

It seems to be breaking the concept that method of class can be called without instantiation of class.

Yeah that is correct, that's why you are getting a pretty clear cut warning as I showed you earlier. You know what a warning does right ? ;). Something that should not be done.

From the PHP Docs..

Calling non-static methods statically generates an E_STRICT level warning.

Source

like image 148
Shankar Narayana Damodaran Avatar answered Dec 18 '22 08:12

Shankar Narayana Damodaran