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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/534159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:00:40  来源:igfitidea点击:

instantiate a class from a variable in PHP?

phpclassvariableseval

提问by Pim Jager

I know this question sounds rather vague so I will make it more clear with an example:

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

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

This is what I want to do. How would you do it? I could off course use eval() like this:

这就是我想要做的。你会怎么做?我当然可以像这样使用 eval() :

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

But I'd rather stay away from eval(). Is there any way to do this without eval()?

但我宁愿远离 eval()。没有 eval() 有没有办法做到这一点?

回答by Paul Dixon

Put the classname into a variable first:

首先将类名放入变量中:

$classname=$var.'Class';

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

This is often the sort of thing you'll see wrapped up in a Factory pattern.

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

See Namespaces and dynamic language featuresfor further details.

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

回答by csga5000

If You Use Namespaces

如果您使用命名空间

In my own findings, I think it's good to mention that you (as far as I can tell) must declare the full namespace path of a class.

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

MyClass.php

我的类.php

namespace com\company\lib;
class MyClass {
}

index.php

索引.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;

回答by flu

How to pass dynamic constructor parameters too

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

If you want to pass dynamic constructor parameters to the class, you can use this code:

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

$reflectionClass = new ReflectionClass($className);

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

More information on dynamic classes and parameters

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

PHP >= 5.6

PHP >= 5.6

As of PHP 5.6 you can simplify this even more by using Argument Unpacking:

从 PHP 5.6 开始,您可以使用Argument Unpacking进一步简化:

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

Thanks to DisgruntledGoat for pointing that out.

感谢 DisgruntledGoat 指出这一点。

回答by zalew

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

$var = 'Test';

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

回答by pickman murimi

I would recommend the call_user_func()or call_user_func_arrayphp methods. You can check them out here (call_user_func_array, call_user_func).

我会推荐call_user_func()call_user_func_arrayphp 方法。您可以在此处查看它们(call_user_func_arraycall_user_func)。

example

例子

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

If you have arguments you are passing to the method , then use the call_user_func_array()function.

如果您有传递给方法的参数,则使用该call_user_func_array()函数。

example.

例子。

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"));