我正在尝试加载一个命名空间和一个名称仅通过变量值知道的类。
我正在尝试这个:
<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分析错误:语法错误,意外的"$arg1"(T_VARIABLE),在第5行的/home/warrant/execute.PHP中应为标识符(T_STRING)
有什么方法可以加载这个,或者我试着用工厂模式来制作它?
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版本&你试过这个吗:
require_once $arg1 . ".class.php";