PHP public function behaves like static

I read a book about PHP when I came across some weird piece of code:

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

    Employee::show();

I came from C ++, so I was going to bet that this code would not work. That is why I tested it.

And it worked, showing "show running" (omg, am I drinking?)!

It seems to violate the concept that a class method can be called without instantiating the class.

  • What is the meaning of a 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 are given as a correct example (if I'm right)

+4
4

, , . , error reporting PHP...

: Employee:: show()

static .

..

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

Employee::show();

...

, , .

, , , . , ?;). -, .

PHP..

E_STRICT .

Source

+11

, php. PHP 4 ( ), ::. PHP 5 .

PHP 5 - . , PHP 5.1.3, :

Strict Standards:  Non-static method Employee::show() should not be called statically in ...
+1

, php. php .

, php.

PHP 5.5.9-1 + sury.org ~ exact + 1 (cli) (: 13 2014 15:53:53)

, .

<?php 
ini_set('display_errors', 1);
error_reporting(E_ALL);

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

    Employee::show();

?>

, .

**Strict Standards: Non-static method Employee::show() should not be called statically in /var/www/test/index.php on line 19
show launched**
+1

Code Works

Strict standards: the non-static Employee :: show () method should not be called static

Just add the static keyword to the function like public static function show()

0
source

Source: https://habr.com/ru/post/1530569/


All Articles