当左侧部分是对象实例时,可以使用->..否则,您将使用::.
这意味着->主要用于访问实例成员(尽管它也可用于访问静态成员,但不鼓励这种使用),而::通常用于访问静态成员(尽管在一些特殊情况下,它用于访问实例成员)。
总体而言,::用于范围分辨率,它可能有一个类名,parent, self,或(在PHP 5.3中)static在左边。parent指所使用的类的超类的作用域;self指使用它的类的作用域;static指“被调用的范围”(请参见后期静态绑定).
规则是::是实例调用当且仅当:目标方法未声明为静态方法。
和
调用时有一个兼容的对象上下文,这意味着这些内容必须为真:调用是从以下上下文发出的
$this存在和
.的阶级
$this是正在调用的方法的类或它的子类。
例子:class A {
public function func_instance() {
echo "in ", __METHOD__, "\n";
}
public function callDynamic() {
echo "in ", __METHOD__, "\n";
B::dyn();
}}class B extends A {
public static $prop_static = 'B::$prop_static value';
public $prop_instance = 'B::$prop_instance value';
public function func_instance() {
echo "in ", __METHOD__, "\n";
/* this is one exception where :: is required to access an
* instance member.
* The super implementation of func_instance is being
* accessed here */
parent::func_instance();
A::func_instance(); //same as the statement above
}
public static function func_static() {
echo "in ", __METHOD__, "\n";
}
public function __call($name, $arguments) {
echo "in dynamic $name (__call)", "\n";
}
public static function __callStatic($name, $arguments) {
echo "in dynamic $name (__callStatic)", "\n";
}}echo 'B::$prop_static: ', B::$prop_static, "\n";echo 'B::func_static(): ', B::func_static(), "\n";$a = new A;$b = new B;echo '$b->prop_instance: ', $b->prop_instance, "\n";//not recommended (static method called as instance method):echo '$b->func_static(): ', $b->func_static(), "\n";echo '$b->func_instance():', "\n", $b->func_instance(), "\n";/* This is more tricky
* in the first case, a static call is made because $this is an
* instance of A, so B::dyn() is a method of an incompatible class
*/echo '$a->dyn():', "\n", $a->callDynamic(), "\n";/* in this case, an instance call is made because $this is an
* instance of B (despite the fact we are in a method of A), so
* B::dyn() is a method of a compatible class (namely, it's the
* same class as the object's)
*/echo '$b->dyn():', "\n", $b->callDynamic(), "\n";
产出:B::$prop_static: B::$prop_static value
B::func_static(): in B::func_static
$b->prop_instance: B::$prop_instance value
$b->func_static(): in B::func_static
$b->func_instance():
in B::func_instance
in A::func_instance
in A::func_instance
$a->dyn():
in A::callDynamic
in dynamic dyn (__callStatic)
$b->dyn():
in A::callDynamic
in dynamic dyn (__call)