参考链接:【PHP中new static()与new self()的区别异同分析】,【PHP中new self()和new static()的区别探究】,【PHP中static和self的区别】
要点其实是理解概念:
还是看看老外的专业解释吧:
self refers to the same class whose method the new operation takes place in.
译:self指那些方法被重写的类。tip:如果继承层次深(如继承深度大于1),当前子类没有重写父类方法,那么就需要找到最后一个方法被重写的类;如果是当前类重写的话,那当然就直接是当前类咯。
static in PHP 5.3's late static bindings refers to whatever class in the hierarchy which you call the method on.
译:static指当你所调用的方法所在的类。tip:其实这个就不用管继承了,永远都是当前类,不用管父类。
一、只有一层继承:
看代码:
class Father { public function getNewFather() { return new self(); } public function getNewCaller() { return new static(); } } class Sun1 extends Father { } class Sun2 extends Father { } $sun1 = new Sun1(); $sun2 = new Sun2(); print '$sun1->getNewFather():'.get_class($sun1->getNewFather()); echo '<br>'; print '$sun1->getNewCaller():'.get_class($sun1->getNewCaller()); echo '<br>'; print '$sun2->getNewFather():'.get_class($sun2->getNewFather()); echo '<br>'; print '$sun2->getNewCaller():'.get_class($sun2->getNewCaller()); echo '<br>'; echo '<br>';
结果:
$sun1->getNewFather():Father $sun1->getNewCaller():Sun1 $sun2->getNewFather():Father $sun2->getNewCaller():Sun2
二、有两层继承
看代码:
class Father { public function getNewFather() { return new self(); } public function getNewCaller() { return new static(); } } class Sun1 extends Father { public function getNewFather() { return new self(); } public function getNewCaller() { return new static(); } } class Sun2 extends Father {} class subSun1 extends Sun1{} class subSub2 extends Sun2{} $sun1 = new Sun1(); $sun2 = new Sun2(); $subSun1=new subSun1(); $subSub2=new subSub2(); print '$sun1->getNewFather():'.get_class($sun1->getNewFather()); echo '<br>'; print '$sun1->getNewCaller():'.get_class($sun1->getNewCaller()); echo '<br>'; print '$sun2->getNewFather():'.get_class($sun2->getNewFather()); echo '<br>'; print '$sun2->getNewCaller():'.get_class($sun2->getNewCaller()); echo '<br>'; echo '<br>'; print '$subSun1->getNewFather():'.get_class($subSun1->getNewFather()); echo '<br>'; print '$subSun1->getNewCaller():'.get_class($subSun1->getNewCaller()); echo '<br>'; print '$subSun2->getNewFather():'.get_class($subSub2->getNewFather()); echo '<br>'; print '$subSun2->getNewCaller():'.get_class($subSub2->getNewCaller());
结果:
$sun1->getNewFather():Sun1
$sun1->getNewCaller():Sun1
$sun2->getNewFather():Father
$sun2->getNewCaller():Sun2
$subSun1->getNewFather():Sun1
$subSun1->getNewCaller():subSun1
$subSun2->getNewFather():Father
$subSun2->getNewCaller():subSub2