从PHP中的变量实例化一个类?

时间:2009-02-10 20:52:32

标签: php class variables eval

我知道这个问题听起来很模糊,所以我会用一个例子说清楚:

$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(),有没有办法做到这一点?

5 个答案:

答案 0 :(得分:188)

首先将类名放入变量:

$classname=$var.'Class';

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

这通常是你在工厂模式中看到的那种东西。

有关详细信息,请参阅Namespaces and dynamic language features

答案 1 :(得分:59)

如何传递动态构造函数参数

如果要将动态构造函数参数传递给类,可以使用以下代码:

$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指出这一点。

答案 2 :(得分:54)

如果使用命名空间

在我自己的调查结果中,我认为你(据我所知)必须声明一个类的完整命名空间路径,这是很好的。

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;

答案 3 :(得分:28)

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

$var = 'Test';

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

答案 4 :(得分:-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"));