完全搞懂php的後期靜態綁定

看了不少人的解釋,都是照搬文檔,說得很是抽象。這裏我舉個例子說明一下,應該不少人能秒懂。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

結合上面的例子和你本身的感悟,再去讀一讀文檔中的說明,是否是清晰了不少?文檔

相關文章
相關標籤/搜索