php中new static和new self的区别

在读Yii2的代码的时候看到的他用了个new static,之前没有用过,所以写了一点代码试了下。差异应该在于new self是实例化当前代码所在类。new static是调用的的那个类,就下面这个例子来说,MyTest继承了Test类, 那么当在MyTest中使用static的时候,这个static代表的就是MyTest,self代表的就是Test。

<?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();

 



文章来自: 本站原创
Tags:
评论: 0 | 查看次数: 13960