Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

Late Static Bindings ใน PHP

บทนำ

คุณสมบัติ late static binding ใน PHP ใช้เพื่ออ้างถึง called class ใน static inheritance เมื่อเรียกเมธอดสแตติก ชื่อคลาสจะถูกแนบกับ scope resolution operator (::) ในขณะที่เมธอด instance อื่นๆ เราเรียกใช้ชื่ออ็อบเจ็กต์ static:: จะไม่ถูก resolve โดยใช้คลาสที่เมธอดถูกกำหนด แตะจะคำนวณโดยใช้ข้อมูล runtime Static references ถึงคลาสปัจจุบันถูก resolve โดยใช้คลาสที่ฟังก์ชันเป็นของ ไม่ใช่ที่มันถูกกำหนด

ตัวอย่าง

ในโค้ดต่อไปนี้ parent class เรียกเมธอดสแตติกด้วย self:: prefix เมธอดเดียวกันเมื่อเรียกด้วย child class ไม่ได้อ้างอิงชื่อ child class เพราะไม่ได้ถูก resolve

ตัวอย่าง

<?php class test1{     public static $name="Raja";     public static function name(){         echo "name of class :" . __CLASS__;     }     public static function getname(){         self::name();     } } class test2 extends test1{     public static function name(){         echo "name of class :" . __CLASS__;     } } test2::getname(); ?>

ผลลัพธ์

name of class :test1

การใช้ static:: แทน self:: สร้าง late binding ใน runtime:

ตัวอย่าง

<?php class test1{     public static function name(){         echo "name of class :" . __CLASS__;     }     public static function getname(){         static::name();     } } class test2 extends test1{     public static function name(){         echo "name of class :" . __CLASS__;     } } test2::getname(); ?>

โค้ดข้างต้นตอนนี้คืนชื่อ child class ตามที่คาดหวัง:

ผลลัพธ์

name of class :test2

การใช้ static:: ในบริบท non-static

เมธอด private ใน parent ถูกคัดลอกไป child ดังนั้น scope จะยังเป็น parent

ตัวอย่าง

<?php class test1{     private function name(){         echo "name of class :" . __CLASS__ ."\n";     }     public function getname(){         $this->name();         static::name();     } } class test2 extends test1{     // } $t2=new test2(); $t2->getname(); ?>

ผลลัพธ์

name of class :test1 name of class :test1

อย่างไรก็ตาม เมื่อ parent method ถูก override scope จะเปลี่ยน:

ตัวอย่าง

class test3 extends test1{     private function name() {         /* original method is replaced; the scope of name is test3 */     } } $t3 = new test3(); $t3->name();

ผลลัพธ์

PHP Fatal error: Uncaught Error: Call to private method test3::name() from context ''