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

 

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

 

比如 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 {}

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

 

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

相关文章:

  • 2021-08-04
  • 2021-07-05
  • 2022-12-23
  • 2021-06-23
  • 2018-06-15
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-12-25
  • 2022-12-23
  • 2022-01-15
  • 2021-10-22
相关资源
相似解决方案