php - PHP父方法覆盖不起作用(使用命名空间)
问题描述
对于代码的每个部分,我都有三个不同的文件。(我使用类自动加载器)。第一个文件(/classes/Test/Foo.php):
<?php
namespace Test;
class Foo
{
public $id;
function __construct(int $id)
{
$this->id = $id;
}
public function get() : string
{
return "FOO:" . $this->id;
}
}
第二个文件(/classes/Test/Bar.php):
<?php
namespace Test;
class Bar extends Foo
{
public function get() : string
{
return "BAR:" . $this->id;
}
}
第三个文件(/index.php):
<?php
namespace Test;
include "autoloader.php";
$bar = new Bar(1);
echo $bar->get();
当我执行第三个文件时,我根本没有得到任何输出,甚至没有错误……但是如果我将所有代码放在一个文件中,它就可以工作。
<?php
namespace Test;
class Foo
{
public $id;
function __construct(int $id)
{
$this->id = $id;
}
public function get() : string
{
return "FOO:" . $this->id;
}
}
class Bar extends Foo
{
public function get() : string
{
return "BAR:" . $this->id;
}
}
$bar = new Bar(1);
echo $bar->get();
输出:酒吧:1
可能是什么问题呢?
自动加载器代码:
<?php
spl_autoload_register(function($class) {
require_once $_SERVER['DOCUMENT_ROOT'] . "/classes/" . str_replace("\\", "/", $class) . ".php";
});
解决方案
自动加载器中所需的文件路径将反映包含命名空间的类名- 这需要与磁盘上的目录结构完全匹配。
在对 , 的回调中spl_autoload_register
,$class
将首先作为Test\Bar传入。这导致它试图包含不存在的文件classes/Test/Bar.php 。这将引发致命错误 - 听起来您的错误报告设置未配置为显示此错误。
对于您发布的文件,您的目录结构需要如下所示:
.
├── classes
│ └── Test
│ ├── Bar.php
│ └── Foo.php
├── autoloader.php
└── index.php
推荐阅读
- maven - 覆盖从 Maven 导入继承的 maven-surefire-plugin 版本
- vba - 何时在访问中使用“我”对象?
- ios - 饼图的标签与小型设备中的饼图重叠
- socket.io - 向客户端发送实时数据:websockets 是最佳选择吗(Vuex 和 Socket.io?
- java - 在 Android 9 中使用 org.apache.http.legacy
- node.js - 你如何循环一个猫鼬查询?
- node.js - Node-config 不会使用 Heroku 中 custom-environment-variables.json 中的变量
- docker - 通过 Cloud Compute Engine 实例部署时,如何为 DOCKER 运行启动脚本?
- windows - 如何对齐自定义凭据提供程序的登录页面中显示的文本
- python-3.x - 对熊猫数据透视表中不同级别的列重新排序