162

我知道这个问题听起来很模糊,所以我将通过一个例子更清楚地说明:

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

4

5 回答 5

238

首先将类名放入变量中:

$classname=$var.'Class';

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

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

有关详细信息,请参阅命名空间和动态语言功能

于 2009-02-10T20:53:52.213 回答
82

如果您使用命名空间

在我自己的发现中,我认为值得一提的是您(据我所知)必须声明一个类的完整命名空间路径。

MyClass.php

namespace com\company\lib;
class MyClass {
}

索引.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;
于 2015-06-04T15:13:26.613 回答
62

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

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

$reflectionClass = new ReflectionClass($className);

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

有关动态类和参数的更多信息

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

于 2012-03-13T14:01:39.920 回答
30
class Test {
    public function yo() {
        return 'yoes';
    }
}

$var = 'Test';

$obj = new $var();
echo $obj->yo(); //yoes
于 2009-02-10T20:56:07.840 回答
-1

我会推荐call_user_func()or call_user_func_arrayphp 方法。你可以在这里查看它们(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"));
于 2017-12-08T23:38:25.157 回答