<?php error_reporting(E_ALL); class Person { public function getClass() { echo get_class($this).PHP_EOL; echo get_class(new self()).PHP_EOL; echo get_class(new static()).PHP_EOL; echo get_class(new parent()).PHP_EOL; } } $person = new Person(); $person->getClass();
- 输出代码,可以看到new parent()报错,由于new parent实例化父类,目前Person不存在父类,所以报错
<?php error_reporting(E_ALL); class Animal{ } class Person extends Animal { public function getClass() { echo get_class($this).PHP_EOL; echo get_class(new self()).PHP_EOL; echo get_class(new static()).PHP_EOL; echo get_class(new parent()).PHP_EOL; } } $person = new Person(); $person->getClass();
- 当Person存在父类的时候,可以发现new parent()实例化的对象是Animal
当存在继承关系时,new self所属于原始类,new static 所属于调用类
<?php error_reporting(E_ALL); class Animal{ public function getClass() { echo get_class(new self()).PHP_EOL; echo get_class(new static()).PHP_EOL; } } class Person extends Animal { } $person = new Person(); $person->getClass();
- $this 和 new self/new static的区别
<?php error_reporting(E_ALL); class Animal{ public $name = 'Animal'; public function getClass() { echo (new self())->name.PHP_EOL; echo $this->name.PHP_EOL; } } $person = new Animal(); $person->name = 'Person'; $person->getClass();
$this是所属类的一个引用,new self表示重新实例化了一个类