繁体   English   中英

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

[英]instantiate a class from a variable in 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(),有没有办法做到这一点?

首先将类名放入变量中:

$classname=$var.'Class';

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

这通常是您将以Factory模式包装的东西。

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

如果您使用命名空间

在我自己的发现中,我认为最好提及您(据我所知)必须声明类的完整名称空间路径。

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;

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

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

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

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

$var = 'Test';

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

我会推荐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"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM