Class definitions in a single file lead to a fatal error

I knew that in PHP you can define a class and regardless of its position in the file, you can use the class. For example, look at the code below:

<?php //First case. No errors. class Second extends First{} class First{}; //Second case. Still nothing. abstract class B extends A{}; class C extends B{}; class A{}; //Fatal error! class C1 extends B1 { }; abstract class B1 extends A1{ }; class A1 { }; ?> 

The first two cases are accurate, but not the last. What for? Is there a rule? Fatal error

PS; I am using PHP 5.6.25, Apache 2.4, CentOS 6.7.

+5
source share
2 answers

I cannot find a written rule for this, but after seeing the result of this:

 <?php //A1 Exists echo class_exists("A1")?"A1 Exists<br>":"A1 Not exists<br>"; //B1 Not exists echo class_exists("B1")?"B1 Exists<br>":"B1 Not exists<br>"; //C1 Not exists echo class_exists("C1")?"C1 Exists<br>":"C1 Not exists<br>"; class C1 extends B1 {}; class B1 extends A1{ }; class A1 { }; ?> 

I can understand that the interpreter can look back and forth to look for the parent class, but when you link the third level of inheritance, it cannot predict that B1 will exist.

If you do:

 <?php //A1 Exists echo class_exists("A1")?"A1 Exists<br>":"A1 Not exists<br>"; //B1 Not exists class B1 extends A1{ }; class A1 { }; ?> 

It says: "Well, I havenโ€™t seen an A1 class announcement before, but I can see that itโ€™s ahead."

+2
source

I apologize, but this is not true, although it looks like this:

I knew that in PHP you can define a class and regardless of its position in the file, you can use the class.

Allows checking documentation

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.

+1
source

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


All Articles