从别名命名空间中的字符串名称创建新的类实例 [英] Create new class instance from string name in an aliased namespace
问题描述
我看到了类似这样的问题和此,但都没有解决如何创建类实例的问题从字符串名称(如果您已经具有名称空间,并且该类位于别名名称空间中):
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;
这将引发PHP Fatal error: Class 'Google' not found
.在这些问题中,它说您应该以__NAMESPACE__
为前缀,但是问题是这些类不在my\project
命名空间中,因此也不起作用,因为它会导致my\project\Google
的类名不存在.
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.
我什至看不到如何使用反射来解决此问题,因为出于相同的原因,我无法为别名类创建反射对象-new \ReflectionClass($provider);
引发相同的错误.
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?
推荐答案
您将只需要使用:
$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.
这篇关于从别名命名空间中的字符串名称创建新的类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!