2015-12-02 110 views
1

我试图加载一个命名空间和一个名字我只知道一个变量的值的类。动态加载命名空间和类

我想这一点:

<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

有任何的方式来加载这个,还是我尝试用工厂模式,使之?

回答

0

据我所知,(不知道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 [email protected] 
Hello! i'm foo class 
~ 
∙ php oskar.php quux          9:59 [email protected] 
Hello! i'm quux class 
Bye! i'm another method 

其实,你可以直接做new $argv[1]但你不能做new $argv[1]->another_method();的xD

0

的PHP版本正在运行&你尝试过这样的:

require_once $arg1 . ".class.php"; 
+0

我的PHP版本PHP 5.6.14-0 + deb8u1,而且我还有chante require_once $ arg1。 “.class.php”;但是有同样的错误。 –