2017-07-24 72 views
0

我想在使用缩短命名空间路径的同时创建一个带有参数的对象以加载函数。它是这样,创建具有变量类名称和名称空间的对象

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 

虽然它会正常工作,如果我只是取代 “默认地将Impl”使用完整路径“Com \ Core \ Service \ Impl”实现Load :: service()内部的实现。

我是新来的。有人可以帮助我,为什么我不能使用缩短路径“Com \ Core \ Service \ Impl as Impl”?

回答

1

同时使用缩短它的命名空间路径。

没有“短命名空间”这样的事情。命名空间或类由它的完整路径决定,从根命名空间开始。

use Com\Core\Service\Impl as Impl; 

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

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

查看更多about namespace aliases/importing

+0

有道理。感谢您的解释。 – nks

0

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

试试这个:

$ucfirstclass = ucfirst($class); 

if (interface_exists('Com\\Core\\Service\\' . $ucfirstclass)) { 
    $ref = 'Com\\Core\\Service\\Impl\\' .$ucfirstclass; 

    return new $ref(); 
} 

仅供参考,请参阅: