首页 > 代码库 > php的static延迟加载

php的static延迟加载

<?phpabstract class Food{    private $cups;    protected $apples;    protected $water;    function __construct(){        $this->cups = static::getCups();//static 也可以调用其他static修饰的函数        $this->apples = static::getApple();        $this->water = $this->getWater();    }    static function create(){        return new static();    }    static function getCups(){        return ‘debault‘;    }    static function getApple(){        return "apple";    }    protected function getWater(){        return "water";    }}class People extends Food{    static function getCups(){        return "Please give me a big bottles";    }    static function getApple(){        return "Please give me a big apple";    }    }echo "<pre>";$app = People::create();var_dump($app);var_dump($app::getCups());echo "</pre>";?>

在>=PHP5.3中,给类加入了关键词static,用于实现延迟静态绑定(late static binding)。

在抽象类里面实例化了这个类,调用了父类的方法,然后父类里面是return new static()
重而创建了一个父类对象

执行结果
我的PHP版本 PHP Version 5.3.28

object(People)#1 (3) {
["cups":"Food":private]=>
string(28) "Please give me a big bottles"
["apples":protected]=>
string(26) "Please give me a big apple"
["water":protected]=>
string(5) "water"
}
string(28) "Please give me a big bottles"