为什么这个$ class工作,$ this-> class不行?

Mih*_*tcu 1 php oop class instance

我有2节课

class A {

   // Do some stuff here!

}
Run Code Online (Sandbox Code Playgroud)

class B {

   public $class = 'A';

   public function getClass(){

      //Case 1
      $class = $this->class;
      return new $class(); //work

      //Case 2
      return new $this->class(); //NOT work
      //or to be precise something like this
      return new {$this->class}(); 

   }

   // Do some other stuff here!

}
Run Code Online (Sandbox Code Playgroud)

为什么将类属性传递给var工作并直接访问NOT,就像你在上面的类中看到的那样,案例1案例2

Aru*_*run 5

原因是

$class = $this->class;
return new $class();
Run Code Online (Sandbox Code Playgroud)

这里$class将包含值"A".所以当你打电话给新人时会得到"A"级$class()

但在

return new $this->class();
Run Code Online (Sandbox Code Playgroud)

它将class()在类"B"中搜索一个函数.所以它不会起作用.

$this用于表示当前的类实例.$this -> something()将始终检查something()同一类中的函数