PHP:从实现接口的类继承

时间:2017-12-14 11:37:25

标签: php php-internals

我有两个文件,让我们说a.php和b.php:

a.php只会:

require 'b.php';
interface testInterface{}
class a implements testInterface{}

b.php:

class b extends a{}

当我运行a.php时,它会抛出这个致命的错误:

  

致命错误:班级' a'在第2行的b.php中找不到

使它更有趣的两个考虑因素:

  • 如果删除课程implements中的a子句,一切正常。

  • 如果我将班级b放在与班级a相同的文件中,而不将其作为外部文件包含在内,那么一切正常。

我无法理解为什么它会抛出这个错误,任何帮助都非常感激。

3 个答案:

答案 0 :(得分:2)

编辑:如果其他人遇到这种情况的可能性很小,我只是偶然发现了这个答案,它可以更好地解释事情:Why can't you inherit from a not-yet-defined class which inherits from a not-yet-defined class?

这个单独的文件方面实际上是无关紧要的 - 您只需简单地定义类/接口就可以重现相同的行为。

我不太了解PHP的内部情况,说为什么会发生任何这种情况,但如果还有一个非常简单的继承结构,那么需要按顺序定义类

此作品

My structure: FIREBASE --> Events ---> UniqueKey1---> Party1 name+some details+ UniqueKey1
                                  ---> UniqueKey2---> Party2 name+some details+ UniqueKey2
                                  ---> UniqueKey3---> Party3 name+some details+ UniqueKey3

这不是:

<?php
class b extends a {}
class a {}

在实现接口时,您可能会产生类似的怪异,如问题所示:

<强>使用:

<?php
class c extends b {}
class b extends a {}
class a {}

不起作用:

<?php
interface testInterface {}
class b extends a implements testInterface {}
class a {}

简而言之:始终按照使用顺序声明接口,类和特征。 PHP 可能能够为你解决问题,但不要依赖它(我怀疑不同的版本也会以微妙的不同方式表现)。几年前由Taylor Otwell在所有人中发表的this question也得出了同样的结论。

答案 1 :(得分:1)

最后放require 'b.php';。应在class a

之前声明class b
interface testInterface{}
class a implements testInterface{}
require 'b.php';

答案 2 :(得分:-1)

在b类中,您继承了类,并且在包含类b之后声明了类a。 PHP从上到下运行。当它包含b.php然后它尝试执行用b.php编写的代码,但是此时没有声明类a。这就是它抛出致命错误并停止进一步执行的原因。

在声明类a后尝试包含b.php -

interface testInterface{}
class a implements testInterface{}
require 'b.php';