首页 > 解决方案 > 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";
});

标签: phpinheritancemethodsnamespacesoverriding

解决方案


自动加载器中所需的文件路径将反映包含命名空间的类名- 这需要与磁盘上的目录结构完全匹配。

在对 , 的回调中spl_autoload_register$class将首先作为Test\Bar传入。这导致它试图包含不存在的文件classes/Test/Bar.php 。这将引发致命错误 - 听起来您的错误报告设置未配置为显示此错误。

对于您发布的文件,您的目录结构需要如下所示:

.
├── classes
│   └── Test
│       ├── Bar.php
│       └── Foo.php
├── autoloader.php
└── index.php

推荐阅读