gpt4 book ai didi

php - 创建具有可变类名和命名空间的对象

转载 作者:行者123 更新时间:2023-12-04 16:53:17 25 4
gpt4 key购买 nike

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

    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"?

最佳答案

while using shorten namespace path in it.



没有“短命名空间”这样的东西。命名空间或类由其完整路径确定,从根命名空间开始。
use Com\Core\Service\Impl as Impl;
Impl在上面的代码片段中是一个 class or namespace alias .别名在编译时解析,并且仅在声明它的文件中有效。

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

阅读更多关于 namespace aliases/importing .

关于php - 创建具有可变类名和命名空间的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45285860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com