【发布时间】:2016-05-16 10:13:04
【问题描述】:
我有两节课
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!
}
为什么将类属性传递给 var 工作并直接访问不是,就像您在上面的类中看到的那样,Case 1 vs. Case 2?
【问题讨论】:
-
因为
return new $this->class();含糊不清....你是说return new ($this->class());还是return new ($this)->class();? (添加括号以显示潜在的歧义) -
仅供参考:上面的确切代码在我的 Linux 服务器和 PHP 5.6.21 中完美运行。
-
它对我有用,正如您对 php 5.6 和 7 所期望的那样
-
在您的声明中放置大括号(根据您的编辑)
return new {$this->class}();消除歧义