php new self()

php里new self() 一般在类内部使用,作用是对自身类实例化

<?php class test{

    public function __construct(){
        echo 'hello';
    }
    public function test2(){
        new self();
    }
}
test::test2();
这个实例会输出hello


后边发现还有个new static()方法,那这个跟new self()有什么区别呢,看代码说话:
class fa {
    public function getfa1() {
        return new self();
    }
    public function getfa2() {
        return new static();
    }
}
$f = new fa();
print get_class($f->getfa1());
echo '<p>';
print get_class($f->getfa2());

get_class()方法是用于获取实例所属的类名

输出:
fa
fa
两个输出都一样,感觉没啥区别呀,后边突发奇想继承下再看看


class er1 extends fa {
}
class er2 extends fa {
}
$er1 = new er1();
$er2 = new er2();
print get_class($er1->getfa1());
echo '<br>';
print get_class($er1->getfa2());
echo '<br>';
print get_class($er2->getfa1());
echo '<br>';
print get_class($er2->getfa2());
输出:
fa
er1
fa
er2


现在输出不一样了,明白new self()与new static()的区别了

只有在继承中才能体现出来,如果没有任何继承,那么这两者是没有区别的,在继承中new self()返回的实例是自己所在的那个类,不管谁调用都是不变的,new static()是由调用者决定的

原文地址:https://www.cnblogs.com/qq254980080/p/9747410.html