The PHP manual for keyword extends says:
Classes must be defined before they are used!
This code executes without error:
class A extends B {}
class B {}
new A();
But this code returns a fatal error – Class ‘B’ not found in…
class A extends B {}
class B extends A {}
new A();
I had assumed a mutual extension (second snippet) would go into recursion by trying to create A, then B, then A, etc.
But, obviously, by the time it tries to create class B, it realizes that A cannot be extended.
Does anyone know the underlying reason for this behavior? Does PHP keep a record of the classes that it attempts to create and know not to try a second time?
Update:
While this snippets works:
class A extends B {}
class B {}
new A();
This one does not:
class A extends B {}
class B extends C {}
class C {}
new A();
So, it seems as @Mike pointed out, you must declare the parent class before extending it. (Although PHP is apparently forgiving in the case of a single child class.) That’s why mutual recursion throws the fatal Class ‘B’ not found error.
Basically yes, a class with a certain name (ignoring namespaces) can only be defined once during script execution. You are essentially trying to define classes multiple (infinite) times.
Is there a reason you would want to do this? It seems pretty illogical to me. Unless you intended to write constructors to prevent it, all I can see is that you’re trying to make an infinite loop of extension … what’s the point? Curiosity? Don’t you remember what happened to the cat?
Edit: To quote the PHP 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 … the order in which the classes are defined is important.” Class B was not found because it had not been declared yet before it was specified as a parent class or A. Reverse the order of your definitions and you’re in the same boat because it’s recursive.