[英]PHP: variable name as class instance
我在類中調用靜態函數時遇到將變量用作類名的問題。 我的代碼如下:
class test {
static function getInstance() {
return new test();
}
}
$className = "test";
$test = $className::getInstance();
我必須將類名稱定義為變量,因為該類的名稱來自數據庫,所以我永遠不知道要創建哪個類的實例。
注意:當前我遇到以下錯誤:
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM
謝謝
$test = call_user_func(array($className, 'getInstance'));
請參閱call_user_func和回調 。
您可以使用反射API ,使您可以執行以下操作:
$className = 'Test';
$reflector = new ReflectionClass($className);
$method = $reflector->getMethod('getInstance');
$instance = $method->invoke(null);
甚至:
$className = 'Test';
$reflector = new ReflectionClass($className);
$instance = $reflector->newInstance();
// or $instance = $reflector->newInstanceArgs([array]);
// or $instance = $reflector->newInstanceWithoutConstructor();
對於我來說,這兩者看起來比將字符串的值直接解釋為類名或使用call_user_func
和friends更加干凈。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.