【问题标题】:Load namespaces and class dynamically动态加载命名空间和类
【发布时间】:2015-12-02 20:29:53
【问题描述】:

我正在尝试加载一个名称空间和一个名称我只知道变量值的类。

我正在尝试这个:

<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/vagrant/execute.php 中的预期标识符 (T_STRING)

有什么方法可以加载这个,还是我尝试用工厂模式来制作?

【问题讨论】:

    标签: php class namespaces


    【解决方案1】:

    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]-&gt;another_method();xD

    【讨论】:

      【解决方案2】:

      您正在运行哪个 PHP 版本以及您是否尝试过:

      require_once $arg1 . ".class.php";
      

      【讨论】:

      • 我的 php 版本是 PHP 5.6.14-0+deb8u1,我也唱过 require_once $arg1 。 “.class.php”;但有同样的错误。
      猜你喜欢
      • 2011-07-23
      • 1970-01-01
      • 2012-08-10
      • 2011-11-19
      • 1970-01-01
      • 2011-08-06
      • 2013-07-19
      • 2015-07-15
      相关资源
      最近更新 更多