new self 與new static的區別

class Test{
        public  function test1(){
            return new self();
        }
        public static function test2(){
            return new static();
        }
    }
    $f = new Test;
     print get_class($f->test1());  //輸出Test
    print get_class($f->test2());  //輸出Test
    
    class Car extends Test{}
    
    $car = new Car;
    print get_class($car->test1());   //輸出Test
    print get_class($car->test2());   //輸出Car

從以上代碼測試可知,如果沒有繼承,那麼new self()與new static()獲取的結果一致,沒有區別。
但是有類的繼承時,new self()獲取的是父類的對象,new static()獲取的是當前類對象

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章