Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expanding PHP namespace alias to full namespace string

Tags:

namespaces

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');

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.

like image 550
Chuck Reed Avatar asked Oct 25 '11 22:10

Chuck Reed


2 Answers

I'm not aware to resolve a string, but the class from an object instance:

use my\namespace\area as MyArea;

$b = new MyArea;
$c = get_class($b);
echo $c; # my\namespace\area

This question is somewhat related: Can't get constant from dynamic class using namespaces.

like image 63
hakre Avatar answered Oct 20 '22 07:10

hakre


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

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

like image 36
Milo Avatar answered Oct 20 '22 07:10

Milo