Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class definitions in the same file cause fatal error

Tags:

php

class

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? Fatal Error

P.S; I'm using PHP 5.6.25, Apache 2.4, CentOS 6.7.

like image 870
undone Avatar asked Oct 17 '22 18:10

undone


1 Answers

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'.

like image 97
MarioZ Avatar answered Oct 20 '22 22:10

MarioZ