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.