![](/img/trans.png)
[英]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.