簡體   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