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 namespace:
<?php
namespace my\project;
require 'vendor/autoload.php';
//Example aliased classes, more may be defined elsewhere
use League\OAuth2\Client\Provider\Google;
use Stevenmaguire\OAuth2\Client\Provider\Microsoft;
//This is mapped from a submitted form value
$provider = 'Google';
$g = new $provider;
This throws PHP Fatal error: Class 'Google' not found
. In those questions, it says you should prefix with __NAMESPACE__
, but the problem is that these classes are not in the my\project
namespace so that doesn't work either, because it results in a class name of my\project\Google
which doesn't exist.
A dumb fix for this specific code would be to use an array to store all the namespaces and class names, but that can't work if I don't know all possible class names in advance.
I can't even see how to use reflection to solve this because I can't create a reflection object for the aliased class for the same reason - new \ReflectionClass($provider);
throws the same error.
How can I get the namespace of an aliased class name dynamically?