php - 动态加载命名空间和类

标签 php class namespaces

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

我正在尝试这样做:

<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/

相关文章:

php - SELECT 包含特定关键字 PHP 的所有行

PHP:mysql 语句有问题。

c# - 为什么一个类型不应该依赖于它包含的命名空间中的类型?

c++ - 命名空间中的静态变量

c# - 返回类实现的接口(interface)类型 C#

php - Laravel 4 - 在验证类中访问身份验证类

php - 30 个唯一变量的 SQL 查询

javascript - 从ajax调用中检索php变量但不起作用

php - 在 Laravel 中向父模型添加作用域

c++ - 错误 : 'object' was not declared in this scope