>method() or $class::method()
Possible Duplicate:
where we use object operator “->” in php
In PHP 5, what are the advantages of typing $class::method()
instead of $class->method()
?
As in any performance or functional differences. Or is this just a way of forcing code non-PHP4 friendly because of the complete rewrite?
In PHP5, the two aren't interchangeable.
Static method calls will perform faster than non-static calls (over many iterations) but then the method is called in the static context and there is no object available to the called method.
The only reason PHP lets you call a non-static method using the static notation was for backwards compatibility in PHP 4 (because PHP 4 didn't have the static modifier for functions, or public/protected/private). If you do call a non-static method statically, you get a warning about "Strict Standards" output, and eventually this may fail with a fatal error.
So the answer really is to call the method the way it was supposed to be called. If it is a static method in PHP 5, then call it statically Class::method()
, if it is a public method, then call it using the object $class->method()
.
Consider this code (run in PHP 5):
class Foo {
protected $bar = 'bar';
function f() {
echo $this->bar;
}
}
echo Foo::f(); // Fatal error: Using $this when not in object context
$class::method()
调用$class::method()
的静态方法,而$class->method()
调用该类的公共标准方法。
上一篇: 符号的含义是什么?