PHP class hoisting bug

When you muck around with PHP enough, every now and then you’ll find a skeleton in the closet.

Hoisting is a mechanism which allows the code to access some defined function/class/interface regardless of where it is declared. For example, I could make an instance of class A on line 1 even if class A isn’t defined until line 3.

$a = new A; // no compile errors

class A { }

PHP also hoists classes that extend other classes which themselves are hoisted.

$b = new B; // no compile errors

class A { }

class B extends A { }

But now comes the strange part. It appears (in at least up to PHP 5.5) that a class which implements an interface is not hoisted!

$c = new C; // Fatal error: Class 'C' not found on line 3

class A { }

interface B { }

class C extends A implements B { }

Yes, rather inconsistent and not even buried in some esoteric condition. So it seems that if you would like to implement an interface (only the foundation of OOP, no big deal) you’ll simply have to ensure that it’s defined before you try to make an instance.

2 thoughts on “PHP class hoisting bug

  1. Since I usually include or require things before I use them, that’s not usually a problem for me. It IS an odd bug though, considering.

  2. Did you ever find a solution to this error? Yours is the only reference to it that I can find. Apparently, you and I are the only ones that have encountered this bug?

Leave a Reply

Your email address will not be published. Required fields are marked *