[PHP] new static()和new self()的区别

当只有一个类,没有任何继承关系的时候,这俩是一样的,也就是返回当前类的实例对象

 

当存在继承关系的时候,两者有区别

 

比如 new self在父类里,调用的时候会返回当前这个类的实例对象

比如 new static在父类里,调用的时候会返回根据当前调用类,返回当前调用类的实例对象

 

<?php

namespace Tests\Unit;
use Tests\TestCase;

class StaticTest extends TestCase
{
    public function testNewStatic(){
        $a=Son::getSelf();
        $b=Son::getStatic();
        var_dump($a,$b);
        $this->assertTrue(true);
    }
}
class Father {
    public static function getSelf() {
        return new self();
    }
    public static function getStatic() {
        return new static();
    }
}
class Son extends Father {}

 

 都是使用Son类调用,self那个返回的Father的对象 ,static是Son的对象

posted @ 2021-08-03 14:49  唯一客服系统开发笔记  阅读(47)  评论(0编辑  收藏  举报