2009-02-10 98 views
109

我知道這個問題聽起來相當含糊,所以我會讓它用一個例子更加清晰:從PHP中的變量實例化類?

$var = 'bar'; 
$bar = new {$var}Class('var for __construct()'); //$bar = new barClass('var for __construct()'); 

這是我想做的事情。你會怎麼做?我可以像這樣使用eval():

$var = 'bar'; 
eval('$bar = new '.$var.'Class(\'var for __construct()\');'); 

但是我寧願遠離eval()。有沒有辦法做到這一點沒有eval()?

回答

160

把類名到一個變量第一:

$classname=$var.'Class'; 

$bar=new $classname("xyz"); 

這往往是那種你會在一個工廠模式看包裹起來的東西。

查看Namespaces and dynamic language features瞭解更多詳情。

+2

這就是我該怎麼做的。請注意,從內部類可以使用父母和自我。 – Ross 2009-02-10 20:55:14

+0

非常感謝。 – 2009-02-10 20:57:06

+1

在類似的筆記上,你也可以做$ var ='Name'; $ OBJ - > { '得到'。是$ var}(); – Mario 2009-02-10 21:04:51

25
class Test { 
    public function yo() { 
     return 'yoes'; 
    } 
} 

$var = 'Test'; 

$obj = new $var(); 
echo $obj->yo(); //yoes 
57

如何通過動態構造函數的參數也

如果要動態構造函數的參數傳遞給類,您可以使用此代碼:

$reflectionClass = new ReflectionClass($className); 

$module = $reflectionClass->newInstanceArgs($arrayOfConstructorParameters); 

More information on dynamic classes and parameters

PHP> = 5.6

從PHP 5.6起,您可以簡化件更更使用Argument Unpacking

// The "..." is part of the language and indicates an argument array to unpack. 
$module = new $className(...$arrayOfConstructorParameters); 

感謝DisgruntledGoat指出了這一點。

43

如果您使用的命名空間

在我自己的調查結果,我認爲這是很好的一提的是你(據我可以告訴)必須聲明一個類的完整的命名空間路徑。

MyClass.php

namespace com\company\lib; 
class MyClass { 
} 

的index.php

namespace com\company\lib; 

//Works fine 
$i = new MyClass(); 

$cname = 'MyClass'; 

//Errors 
//$i = new $cname; 

//Works fine 
$cname = "com\\company\\lib\\".$cname; 
$i = new $cname; 
-1

我會建議call_user_func()call_user_func_array PHP方法。 你可以在這裏查看(call_user_func_arraycall_user_func)。

例如

class Foo { 
static public function test() { 
    print "Hello world!\n"; 
} 
} 

call_user_func('Foo::test');//FOO is the class, test is the method both separated by :: 
//or 
call_user_func(array('Foo', 'test'));//alternatively you can pass the class and method as an array 

如果你有要傳遞到方法參數,然後使用call_user_func_array()功能。

示例。

class foo { 
function bar($arg, $arg2) { 
    echo __METHOD__, " got $arg and $arg2\n"; 
} 
} 

// Call the $foo->bar() method with 2 arguments 
call_user_func_array(array("foo", "bar"), array("three", "four")); 
//or 
//FOO is the class, bar is the method both separated by :: 
call_user_func_array("foo::bar"), array("three", "four"));