【问题标题】:Create object with variable class name and namespace创建具有变量类名和命名空间的对象
【发布时间】:2017-12-30 08:24:54
【问题描述】:

我正在尝试创建一个带有加载器函数参数的对象,同时在其中使用缩短命名空间路径。就像,

    use Com\Core\Service\Impl as Impl;

    class Load {
        public static function service(String $class, array $params = array()){
            try {
                $ucfirstclass = ucfirst($class);
                if (interface_exists('\\Com\\Core\\Service\\' . $ucfirstclass)) {
                    $ref = "Impl\\".$ucfirstclass;
                    return new $ref();
                } else {
                    throw new Exception("Service with name $class not found");
                }
            } catch (\Throwable $ex) {
                echo $ex->getMessage();
            }
        }
    }

虽然这样称呼它,

    $userService = Load::service("user"); 

抛出异常

    Class 'Impl\User' not found

虽然我将 Load::service() 实现中的“Impl”替换为完整路径“Com\Core\Service\Impl”,但它会正常工作。

我是新手。有人可以在这里帮忙,为什么我不能使用缩短路径“Com\Core\Service\Impl as Impl”?

【问题讨论】:

    标签: php class object namespaces php-7


    【解决方案1】:

    同时在其中使用缩短命名空间路径。

    没有“短命名空间”之类的东西。命名空间或类由其完整路径确定,从根命名空间开始。

    use Com\Core\Service\Impl as Impl;
    

    上述代码片段中的Implclass or namespace alias。别名在编译时解析,仅在声明它的文件中有效。

    在运行时不能使用别名。在运行时引用类名的唯一方法是生成其绝对路径(从根命名空间开始)。
    你已经发现了这一点。

    阅读更多关于namespace aliases/importing的信息。

    【讨论】:

    • 有道理。谢谢你的解释。
    【解决方案2】:

    当将类名称为strings 时,您始终必须使用完全限定的类名。

    试试这个:

    $ucfirstclass = ucfirst($class);
    
    if (interface_exists('Com\\Core\\Service\\' . $ucfirstclass)) {
        $ref = 'Com\\Core\\Service\\Impl\\' .$ucfirstclass;
    
        return new $ref();
    }
    

    参考见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-28
      • 1970-01-01
      • 2013-11-14
      • 2011-05-08
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 2011-12-18
      相关资源
      最近更新 更多