<?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();
<?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();
当存在继承关系时,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();
<?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表示重新实例化了一个类
PHP内部new self/new parent/new static/$this的差别
原文:https://www.cnblogs.com/ywjcqq/p/13588181.html