【发布时间】:2016-07-25 17:33:00
【问题描述】:
我见过像this 和this 这样的问题,但是如果您已经有一个命名空间并且该类位于别名命名空间中,这两个问题都没有解决如何从字符串名称创建类实例:
<?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 '不存在。
对此特定代码的一个愚蠢的解决方法是使用一个数组来存储所有命名空间和类名,但如果我事先不知道所有可能的类名,那将无法工作。
我什至看不到如何使用反射来解决这个问题,因为出于同样的原因,我无法为别名类创建反射对象 - new \ReflectionClass($provider); 抛出相同的错误。
如何动态获取别名类名的命名空间?
【问题讨论】:
-
试试
use League\OAuth2\Client\Provider\Google as Google -
@Xorifelse,不,这和我的一样
标签: php namespaces