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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With