[英]PHP: Is it possible to get the name of the class using the trait from within a trait static method?
[英]Possible to instantiate a PHP instance using a class name property from within a class method (in one line of code)?
我希望能够使用存储在另一个类的属性中的类名来实例化一个类,并且我想用一行代码执行此操作,如下面代码中的注释(并且它应该至少在一个PHP 5的版本。 这可能吗?
<?php
class Foo {
public function doFoo() {
echo "foo\n";
}
}
class Bar {
function __construct($className) {
$this->className = $className;
}
public function doBar() {
//INSTEAD OF THESE TWO LINES...
//$className = $this->className;
//$instance = new $className();
//I WOULD LIKE THIS (OR SOME OTHER) ONE-LINER TO WORK:
$instance = $this->className();
$instance->doFoo();
}
}
$bar = new Bar('Foo');
$bar->doBar();
预期产量:
foo
在代码中有一个明显的拼写错误,它调用函数而不是构造函数,并且可以修复如下:
$instance = new $this->className();
这就是诀窍。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.