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条)

报告相同问题?