PHP difference in access to class methods

What is the difference between $foo->bar()and $foo::bar()?

+3
source share
2 answers

$foo::bar()- This is a call to a static method bar(), that is, the object was $foonot called by the method __construct().

When called, the $foo->bar()object $foomust be instructed before! Example:

$foo = new Foo; // internally the method __constuct() is called in the Foo class!
echo $foo->bar(); 

Often you do not call a static method on an existing object, as in the example ( $foo), you can call it directly in the Foo class:

 Foo::bar();
+4
source

With the first

$foo->bar();

you call the (object) methods whereas

Foo::bar();

you call class methods (static).

It can be called class methods for objects. That is what your second example does. So this is

$foo = new Foo;
$foo::bar();

coincides with

Foo::bar();

or even

$classname = get_class($foo);
$classname::bar();

: - $foo .

$foo = 'Baz';
$foo::bar(); // Baz::bar();
0

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


All Articles