为什么 $class 有效而 $this->class 无效?

Why this $class works and $this->class not?

我有 2 个 classes

class A {

   // Do some stuff here!

}

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!

}

为什么将 class 属性 传递给 var 工作并直接访问不是,就像您在上面的 class 中看到的那样,案例 1 对比 案例 2 ?

原因是

$class = $this->class;
return new $class();

此处 $class 将包含值 "A"。所以当你调用 new $class()

时它会得到 class "A"

但是在

return new $this->class();

它将在 class "B" 中搜索函数 class()。所以不行。

$this 代表当前的 class 实例。 $this -> something() 将始终在同一个 class

中检查函数 something()

是的,原因是你做错了,

这就是你要做的,

class A {

  public $class = 'A';

  function __construct() {
    # code...
  }

  public function getClass(){
    return $this;
  }

  public function instance () {
    return $this->class;
  }
}

获取object/A

$obj = new A();
$new_obj = $obj->getClass();

获取实例/$class的值,

$inst = $obj->instance();

$this指的是class本身,

似乎对我有用,如果我删除 '()' :).

return new $this->class; //Work just fine without parentheses

注:我用的是PHP5.4.16