看了不少人的解释,都是照搬文档,说得很是抽象。这里我举个例子说明一下,应该不少人能秒懂。php
<?php interface FactoryInterface { public function create(); } abstract class Factory implements FactoryInterface { public static $instance = null; public function create() { throw new \Exception('Please implement create method.'); } public static function getInstance() { if (is_null(self::$instance)) { self::$instance = new static(); } return self::$instance; } } class Car { public function run() { echo "I'm running"; } } class CarFactory extends Factory { public function create() { return new Car(); } } CarFactory::getInstance()->create()->run();
上面这个抽象类的getInstance
静态方法中,我想实例化一个子类,怎么办?除了new static
, 没有别的方法,由于你根本不知道子类的名称究竟是什么,它能够被命名成任意合法的名称。
还有其它场景,好比说在父类的静态方法中调用子类的静态方法,怎么办?也是同样static::childMethod()
code
结合上面的例子和你本身的感悟,再去读一读文档中的说明,是否是清晰了不少?文档