1. 程式人生 > >【PHP趣味】new self和new static的區別

【PHP趣味】new self和new static的區別

<?php

class Test {
    private $_user;
    protected function __construct($user) {
        $this->_user = $user;
    }
    public function showUser() {
        echo "{$this->_user}\n";
    }
    public static function of($user) {
        return new static($user);
    }
}

class MyTest extends Test {
    protected function __construct($user) {
        parent::__construct('from MyTest: '.$user);
}

}

class Test2 {
    private $_user;
    protected function __construct($user) {
        $this->_user = $user;
    }

    public function showUser() {
        echo "{$this->_user}\n";
    }

    public static function of($user) {
        return new self($user);
    }
}

class MyTest2 extends Test2 {
    protected function __construct($user) {
        parent::__construct('from MyTest: '.$user);
    }
}

MyTest::of("hello world")->showUser();
MyTest2::of("hello world")->showUser();

輸出結果:

from MyTest: hello world

hello world

小結:

一般情況下new self就是例項化這行程式碼所在的類,但如果是子類呼叫父類的方法(如上面父類的of),在這個父類方法裡實例化子類,就可以new static來實現(換句話說new static實現了在父類裡實例化子類),這也是多型的體現,讓程式更加靈活。(在YII框架中有應用)