dongyue0225
2013-10-28 18:05
浏览 149
已采纳

使用PHP变量实例化一个类 - 命名空间的问题

All examples below are based on the guarantee that all files exist in their correct location. I've treble checked this.

(1) This works when NOT using namespaces:

$a = "ClassName";
$b = new $a();

This doesn't work:

// 'class not found' error, even though file is there

namespace path\to\here;
$a = "ClassName";
$b = new $a();

This DOES work:

namespace path\to\here;
$a = "path\to\here\ClassName";
$b = new $a();

So it seems the namespace declaration is ignored when using a variable to instantiate a class.

Is there a better way (than my last example) so I don't need to go through some code and change every variable to include the namespace?

图片转代码服务由CSDN问答提供 功能建议

以下所有示例都基于所有文件都存在于正确位置的保证。 我已经高音检查了这个。

(1)这在不使用名称空间时有效:

  $ a =“ClassName”; \  n $ b = new $ a(); 
   
 
 

这不起作用:

  //'  class not found'错误,即使文件在那里
 
namespace path \ to \ here; 
 $ a =“ClassName”; 
 $ b = new $ a(); 
   
 
 

此DOES有效:

 命名空间路径\到\ here; 
 $ a =“path \ to \ here \ ClassName”; 
  $ b = new $ a(); 
   
 
 

因此,当使用变量实例化类时,似乎忽略了名称空间声明。 \ n

有没有更好的方法(比我上一个例子)所以我不需要经历一些代码并更改每个变量以包含命名空间?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题