当左边部分是一个对象实例时,你使用->。否则,您使用::。
这意味着->主要用于访问实例成员(虽然它也可以用于访问静态成员,但不鼓励这种用法),而::通常用于访问静态成员(尽管在少数特殊情况,用于访问实例成员)。
一般来说,:: 用于scope resolution,它的左边可能有一个类名parent、self 或(在 PHP 5.3 中)static。 parent 指使用它的类的超类的范围; self 指使用它的类的范围; static 指的是“被调用范围”(参见late static bindings)。
规则是带有:: 的调用是实例调用当且仅当:
- 目标方法未声明为静态和
- 在调用时有一个兼容的对象上下文,这意味着这些必须是真的:
- 调用是从存在
$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 值
B::func_static(): 在 B::func_static
$b->prop_instance: B::$prop_instance 值
$b->func_static(): 在 B::func_static
$b->func_instance():
在 B::func_instance
在 A::func_instance
在 A::func_instance
$a->dyn():
在 A::callDynamic
在动态 dyn (__callStatic)
$b->dyn():
在 A::callDynamic
在动态 dyn (__call) 中