I knew that in PHP you could define a class and regardless of its position in the file, you could use the class. For example, take a 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 { };
?>
First two cases are fine but not the last one. Why? Is there any rule?
P.S; I'm using PHP 5.6.25, Apache 2.4, CentOS 6.7.
I can't find a written rule for that, but 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 figure out that the interpreter can look back and forward to look for the parent class, but when you chain a third level of inheritance it can't predict that B1 is going to 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 'ok, I didn't see class A1 declaration before, but I see that it is ahead'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With