3
class A extends B {}
class B extends C{}
class C {}

result

PHP Fatal error: class 'B' not found ...

if the order is like this

class A extends B {}
class C {}
class B extends C{}

everything is ok.


PS: if I remove class C {}

class A extends B {}
class B extends C{}

php tells me class 'B' is not found, why?

php version 5.3.4

limboy
  • 3,879
  • 7
  • 37
  • 53

5 Answers5

5

The PHP manual clearly mentions:

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. If you want to create another class called Yellow_named_cart based on the class Named_Cart you have to define Named_Cart first. To make it short: the order in which the classes are defined is important.

codaddict
  • 445,704
  • 82
  • 492
  • 529
  • It sometimes works, I have not understood why perfectly. But if you follow the rule to only use classes after you have defined them, you're safe. – hakre Jun 15 '11 at 11:21
2

clearly a parser bug

this works

class A extends B {}
class B {}

this doesn't

class C extends D {}
class D extends E {}
class E {}

consider reporting on bugs.php.net

user187291
  • 53,363
  • 19
  • 95
  • 127
  • I think one class is on the house. That would be class D. But it extends from E, so it's not looked further. Probably worth to report for clarification in the docs. – hakre Jun 15 '11 at 11:19
0

Class order matters in PHP definitions.

Does the order of class definition matter in PHP?

This is why you don't have visibility of the class defined after the one you are defining (in this case class A cant see class B because it is defined after).

Community
  • 1
  • 1
VAShhh
  • 3,494
  • 2
  • 24
  • 37
0

Because php is interpreted rather than compiled the order of declaration must be valid. In this example class B doesn't exist for A to extend.

Dormouse
  • 5,130
  • 1
  • 26
  • 42
0

Obivously class B is not defined in the moment you trying to extend it, because it occurs after extends B. Its not a bug, its the way the world works: You can only use, what exists ;)

KingCrunch
  • 128,817
  • 21
  • 151
  • 173