douqi1212 2017-07-24 16:41
浏览 138
已采纳

使用变量类名和命名空间创建对象

I am trying to create an object with a parameter to loader function while using shorten namespace path in it. It goes like,

    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();
            }
        }
    }

While calling it like,

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

it is throwing an exception

    Class 'Impl\User' not found

Though it'll work fine if I'll just replace "Impl" inside Load::service() implementation with full path "Com\Core\Service\Impl".

I'm new with this. Can someone help here why can't I use shorten path "Com\Core\Service\Impl as Impl" ?

  • 写回答

2条回答 默认 最新

  • drslez4322 2017-07-24 18:00
    关注

    while using shorten namespace path in it.

    There is no such thing as "short namespace". A namespace or a class is determined by its complete path, starting from the root namespace.

    use Com\Core\Service\Impl as Impl;
    

    Impl in the above fragment of code is a class or namespace alias. An alias is resolved at the compile time and it is valid only in the file where it is declared.

    It is not possible to use an alias during the runtime. The only way to refer to a class name during runtime is to generate its absolute path (starting from the root namespace).
    You already discovered this.

    Read more about namespace aliases/importing.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 基于信创PC发布的QT应用如何跨用户启动后输入中文
  • ¥20 非root手机,如何精准控制手机流量消耗的大小,如20M
  • ¥15 远程安装一下vasp
  • ¥15 自己做的代码上传图片时,报错
  • ¥15 Lingo线性规划模型怎么搭建
  • ¥15 关于#python#的问题,请各位专家解答!区间型正向化
  • ¥15 unity从3D升级到urp管线,打包ab包后,材质全部变紫色
  • ¥50 comsol温度场仿真无法模拟微米级激光光斑
  • ¥15 上传图片时提交的存储类型
  • ¥15 VB.NET如何绘制倾斜的椭圆