【问题标题】:class not found when extending class that implements interface in PHP扩展在 PHP 中实现接口的类时找不到类
【发布时间】:2012-01-10 08:36:06
【问题描述】:
<?php

class A extends B {}

class B implements C {}

interface C {}

上面的代码抛出“致命错误:找不到类'B'”... 它是一个php错误吗?还是?

环境:“带有 Suhosin-Patch (cli) 的 PHP 5.3.6-13ubuntu3.2(构建时间:2011 年 10 月 13 日 23:19:13) 版权所有 (c) 1997-2011 PHP 集团 Zend Engine v2.3.0,版权所有 (c) 1998-2011 Zend Technologies 使用 Xdebug v2.1.0,版权所有 (c) 2002-2010,作者 Derick Rethans "

【问题讨论】:

  • 就是所有的代码吗?此外,如果 C 尚未创建(订单),则不能调用它

标签: php


【解决方案1】:

您在类定义的顺序方面特别有问题。只要接口定义在同一个文件中,就可以在任何地方声明——但类必须先定义,然后才能扩展。

以下是 PHP 中完全有效的顺序:

class B implements C { ... }
class A extends B { ... }
interface C { ... }

a closed bug requesting clarification in the PHP5 docs

对类似问题 (Does the order of class definition matter in PHP?) 的回答提到了Autoloading。如果您使用多个文件,您可能需要对此进行调查。

【讨论】:

  • 正是我想要的。谢谢。我想知道他们为什么不能一次扫描整个文件...
【解决方案2】:

您以错误的顺序声明类和接口。这是正确的:

interface C {}

class B implements C {}

class A extends B {}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 2012-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多