->
เมื่อส่วนด้านซ้ายเป็นวัตถุเช่นคุณใช้ ::
มิฉะนั้นคุณใช้
ซึ่งหมายความว่า->
ส่วนใหญ่จะใช้ในการเข้าถึงสมาชิกอินสแตนซ์ (แม้ว่าจะสามารถใช้ในการเข้าถึงสมาชิกแบบคงที่การใช้งานดังกล่าวหมดกำลังใจ) ในขณะที่::
มักจะใช้ในการเข้าถึงสมาชิกแบบคงที่ (ในบางกรณีพิเศษ )
โดยทั่วไป::
จะใช้สำหรับความละเอียดขอบเขตและมันอาจมีทั้งชื่อชั้น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 ค่า
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)