php中“延迟静态绑定”的使用

来源:互联网 发布:如何优化公司人力成本 编辑:程序博客网 时间:2024/05/16 18:25
 1 <?php 2  3 class ParentBase { 4  5   static $property = 'Parent Value'; 6  7   public static function render() { 8  9     return self::$property;10 11   }12 13 }14 15 class Descendant extends ParentBase {16 17   static $property = 'Descendant Value';18 19 }20 21 echo Descendant::render();22 23 Parent Value


在 这个例子中,render()方法中使用了self关键字,这是指ParentBase类而不是指Descendant类。在 ParentBase::render()方法中没法访问$property的最终值。为了解决这个问题,需要在子类中重写render()方法。

通过引入延迟静态绑定功能,可以使用static作用域关键字访问类的属性或者方法的最终值,如代码所示。


class Human{static public $head=1;static public $leg=45;static public function eat(){echo self::$head;}static public  function run(){echo static::$leg;}}class animal extends Human{static public $leg=10;}class Stu extends animal{static public $head=2;static public $leg=4;}Stu::eat();  // 1 这里的eat函数是在Human里面的 所以self::$head 代表的是Human类echo '<br>';Stu::run(); // static 就是延时绑定    //显示的类属性的最终值  所以不是animal的$leg=10 而是Stu 的$leg=4

通 过使用静态作用域,可以强制PHP在最终的类中查找所有属性的值

原创粉丝点击