Create new class instance from string name in an aliased namespace

后端 未结 2 945
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-25 16:59

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

相关标签:
2条回答
  • 2021-01-25 17:41

    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.

    0 讨论(0)
  • 2021-01-25 18:01

    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.

    0 讨论(0)
提交回复
热议问题