A class that implements the interface must be declared before the children?

I came across an interesting problem today. In the context of a single file for multiple declarations, if class B implements interface A , and class C extends class A , class class B must be declared before class C

The following code does not work:

 interface A {} class C extends B {} // Class 'B' not found class B implements A {} 

This fixes:

 interface A {} class B implements A {} class C extends B {} // Class 'B' is found 

But this works great:

 class A {} class C extends B {} // Class 'B' is found class B extends A {} 

These are my results on PHP 5.3.8 (Win32) and PHP 5.3.3-1ubuntu9.6 w / suhosin.

So the question is: is this documented behavior? . Why will it work with classes, but not with interfaces? Or should this be considered a mistake?

Let me know about your experience before I start digging the PHP source code and / or opening a ticket with a PHP error. :)

Thanks!

Note. I know this is just a matter of determining the order of the class, but it puzzles me ... If this is inappropriate, please feel free to close it.

+6
source share
1 answer

Yes, this is documented behavior:

Inheritance of objects (Note) :

If autoload is not used, classes must be defined before they are used. If the class extends another, then the parent class must be declared before the child structure of the class. This rule applies to a class that inherits from other classes and interfaces.

PHP: extends - Manual (Note)

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


Undefined Behavior (with added sarcasm)

Although your third example may add up, he did not say that it was working in accordance with the documentation (and I can not find the entry in the change log, which indicates that it is included).

The PHP documentation, unfortunately, is not 100%, but you can only trust what you know, and the above quotes are all I can find on this.

You can call it a mistake, but in C ++ we will describe it as undefined behavior ie. what you can’t rely on.


If the β€œstandard” (documentation) does not mention this, it is unsafe to use.

If the "standard" (documentation) does not mention this, it can lead to a universe explosion - or a predator jumping through your window. Do not do anything to kill us all!

+8
source

Source: https://habr.com/ru/post/904091/


All Articles