I\'ve seen questions like this and this, but neither addresses how to create a class instance from a string name if you already have a namespace and the class is in an aliased n
You will simply have to use:
$provider = 'League\OAuth2\Client\Provider\Google';
There is no other solution, class name variables need to contain the fully qualified class name; aliasing doesn't apply to string class names, and introspection can't help you either.
Namespaces are introduced to allow same names in different contexts, so the answer is: no, it is not possible.
You can have a class \League\OAuth2\Client\Provider\Google
and another class \League\OAuth1\Client\Provider\Google
: in this case, how you can determine what class to instantiate?
Assuming you know that there are only unique class names, you can use this code:
$provider = 'Google';
$found = False;
foreach( get_declared_classes() as $class )
{
if( preg_match( "~(.*\\\)?($provider)$~", $class ) )
{
$found = $class;
break;
}
}
if( $found )
{
$g = new '\\'.$found;
}
else
{
echo "No '$provider' class found";
}
demo with DateTime class
but this routine is only a simplification of your idea “to use an array to store all the namespaces and class names”, because — even with above code — if you don't know all declared classes, you can obtain unwanted results.