我正在尝试加载一个命名空间和一个名称的类,我只知道一个变量的值。
我正在尝试这样做:
<php
/**
* Namespaces and class have the same name.
*/
require_once($arg1 . '.class.php');
use \$arg1\$arg1;
/**
* also I have try
* use \{$arg1}\{$arg1};
*/
$object = new $arg1();
var_dump($object);
?>
它让我回来:
PHP Parse error: syntax error, unexpected '$arg1' (T_VARIABLE), expecting identifier (T_STRING) in /home/vagrant/execute.php on line 5
有什么方法可以加载它,或者我尝试使用工厂模式来制作它?
最佳答案
AFAIK,(不确定 PHP7)在命名空间调用中链接变量或常量是不可能的。
如果您只想根据变量中的变化值加载一个类(来自 $argv 或 $_GET 或其他),我通常会执行以下操作:
(这是一个控制台脚本)
<?php
class foo {
function foo() {
print "Hello! i'm foo class \n";
}
}
class quux {
function quux() {
print "Hello! i'm quux class \n";
}
function another_method() {
print "Bye! i'm another method \n";
}
}
$var = $argv[1];
$obj = new $var;
if ("quux" == $var){
$obj->another_method();
}
这是我得到的输出:)
∙ php oskar.php foo 9:58 leandro@montana
Hello! i'm foo class
~
∙ php oskar.php quux 9:59 leandro@montana
Hello! i'm quux class
Bye! i'm another method
其实你可以做
new $argv[1]
直接但你不能做new $argv[1]->another_method();
xD
关于php - 动态加载命名空间和类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34052394/