PHP difference in accessing class methods
What's the difference betw开发者_开发百科een $foo->bar()
and $foo::bar()
?
$foo::bar()
is a call of the static method bar()
, that means the object $foo
was not instanciated by the __construct()
method.
When calling $foo->bar()
, the object $foo
has to be instanciated before! Example:
$foo = new Foo; // internally the method __constuct() is called in the Foo class!
echo $foo->bar();
Often you don't call a static method on a existing object like in you example ($foo
), you can call it directly on the class Foo:
Foo::bar();
With the first one
$foo->bar();
you call (object) methods, whereas with
Foo::bar();
you call class (static) methods.
Its possible to call class methods on objects. That is, what your second example does. So this
$foo = new Foo;
$foo::bar();
is identical to
Foo::bar();
or even
$classname = get_class($foo);
$classname::bar();
Update:
Missed something
$foo
can also just be a string with a classname.
$foo = 'Baz';
$foo::bar(); // Baz::bar();
精彩评论