>没有错误 b.php >>> fatal error :在第 2 行的 b.php 中找不到类“B” 根据 [php.net manual] : Clas-6ren">
gpt4 book ai didi

php - php手册中关键字 "Classes must be defined before they are used "如何理解 "extends"

转载 作者:搜寻专家 更新时间:2023-10-31 21:11:37 26 4
gpt4 key购买 nike

我得到 2 个 php 文件一个.php

<?php
class A extends B {}
class B{}

php a.php
>>>没有错误

b.php

<?php
class A extends B {}
class B extends C {}
class C{}

php b.php
>>>> fatal error :在第 2 行的 b.php 中找不到类“B”

根据 [php.net manual] :

Classes must be defined before they are used! If you want the class Named_Cart to extend the class Cart, you will have to define the class Cart first. If you want to create another class called Yellow_named_cart based on the class Named_Cart you have to define Named_Cart first. To make it short: the order in which the classes are defined is important.

所以任何人请解释为什么 a.php 没有“ fatal error ”。

最佳答案

根据 PHP Inheritence文档。

Unless autoloading is used, then classes must be defined before they are used. If a class extends another, then the parent class must be declared before the child class structure. This rule applies to classes that inherit other classes and interfaces.

这个例子没有类 B 和 D 的依赖:

<?php
//This will work
class A extends B {} //searches for class B in current document
class B {}

class C extends D{}
class D{}

B类依赖于C类

<?php
//This will not work
class A extends B {} //searches for class B in current document but class B has dependencies
class B extends C {}
class C{}

对于包含和要求,您必须先包含该文件,然后才能在该文件中使用声明的函数/类。

另见 autoloading .

关于php - php手册中关键字 "Classes must be defined before they are used "如何理解 "extends",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18458992/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com