Skip to content

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!

$b = new B; // Fatal error: Class 'B' not found

class A { }

class B extends A implements C { }

Interface C { }

Yes, rather inconsistent and not even buried in some esoteric condition. So it seems that if you would like to implement an interface you’ll have to ensure that it’s defined before you try to create an instance.