将PHP名称空间别名扩展为完整的名称空间字符串 [英] Expanding PHP namespace alias to full namespace string

查看:69
本文介绍了将PHP名称空间别名扩展为完整的名称空间字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以扩展别名的PHP名称空间令牌以获取完整的名称空间标识符.这样做的目的是使我们的对象创建工厂期望一个带有完整名称空间的字符串,以便它可以自动加载它.这是一个简单的示例:

I was wondering if there is a way to expand an aliased PHP namespace token to get the full namespace identifier. The purpose of doing so is that our object creation factory expects a string with the full namespace so it can autoload it. Here's a quick example:

<?php

use my\namespace\area as MyArea;

$goodObject = MyApp::factory('my\namespace\area\ClassName');
$badObject = MyApp::factory('MyArea\ClassName');


我正在寻找一种通用的解决方案,以便在任何情况下都可以扩展NS别名,等效于:


I am looking for some generic solution to be able to expand that NS alias out in any situation, with something equivalent to:

$desiredObject = MyApp::factory(resolve_namespace_alias('MyArea') . '\ClassName');

如果外面有人解决了这个问题,我很想听听您是如何做到的.

If anyone out there has tackled this issue, I would love to hear about how you did it.

推荐答案

自PHP 5.5起,您可以使用MyArea::class(

Since PHP 5.5 you can use MyArea::class (https://wiki.php.net/rfc/class_name_scalars).

在PHP 5.3+中,您可以使用AliasExpander::expand('MyArea')( https://github.com/milo/utils #aliasexpander ).

In PHP 5.3+ you can use AliasExpander::expand('MyArea') (https://github.com/milo/utils#aliasexpander).

这篇关于将PHP名称空间别名扩展为完整的名称空间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆