好的,我创建了 3 个文件,其中有 index.php
,其中包含 namespace.php
,其中有 2 个函数:
Namespace namespaceName{
class classLoader{
public function __construct() {
//not used
}
public function executeFunctionOutsideTheNamespace() {
include("class.php");
new classExtended("badass");
}
}
class classBase{
public function __construct(){
}
}
}
现在,从 index.php
中,我尝试动态地调用第三个文件 class.php
中的函数,其中是一个从 namespaces< 扩展一个类的类
。这是class.php
代码
class classExtended extends namespaceName\classBase
{
public function __construct($action) {
echo $action;
}
}
当然还有我的 index.php
文件
require("namespace.php");
$namespace= new namespaceName\classLoader();
$oController = $namespace->executeFunctionOutsideTheNamespace();
$oController
是 classLoader()
的实例,对吗?现在我从命名空间 namespaceName
的类 classLoader()
调用函数 executeFunctionOutsideTheNamespace
,并告诉 include("class.php") ;
并实例化扩展类,它是来自命名空间的 classBase 的扩展。我记下了一个 fatal error :第 10 行的 C:\xampp\htdocs\exercices\namespace.php 中找不到类 'namespaceName\classExtended'
最佳答案
事实上,class.php
被 include()
包含在 classLoader
类中,该类位于 namespaceName
命名空间不会导致它从包含文件继承命名空间。
因此,包括 class.php
将类 classExtended
加载到全局命名空间中,这意味着要按代码访问它,您需要使用
new \classExtended("cool");
为了将 classExtended
放入命名空间 namespaceName
中,因为它驻留在其自己的文件中,您需要在该文件中声明命名空间。这样做还意味着您需要从 extends
声明中删除 namespaceName
,以免 PHP 开始寻找嵌套的 namespaceName\namespaceName\classBase
。文件 class.php
必须变为
namespace namespaceName;
// Declare the class without the namespace in extends
// since classExtended is now in the same namespace as classBase
class classExtended extends classBase
{
public function __construct($action) {
echo $action;
}
}
我强烈建议您熟悉 PSR-4 class autoloading standard由 PHP 框架互操作性组定义,并使用 Composer处理你的类自动加载。然后,命名空间主要变成文件系统布局的问题,并且文件包含会自动处理。
关于php - 命名空间内所需的类无法实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27669716/