PHP and circular dependencies

Today I noticed the strangest bug in PHP. Apparently there's a problem with circular dependencies and interfaces.

This is how the problem occurs:

  1. <?php
  2.  
  3. // this is class1.php
  4.  
  5. require_once 'iclass.php';
  6.  
  7. class class1 implements iclass {
  8.  
  9. }
  10.  
  11. ?>
  1. <?php
  2.  
  3. // this is class2.php
  4.  
  5. require_once 'class1.php';
  6.  
  7. class class2 extends class1 {
  8.  
  9. }
  10.  
  11. ?>
  1. <?php
  2.  
  3. // this is iclass.php
  4.  
  5. require_once 'class2.php';
  6.  
  7. interface iclass {
  8.  
  9. function setSomething(class2 $object);
  10.  
  11. }
  12.  
  13. ?>

Now, if you run class1.php, you will get the following error:

  1. Fatal error: Class 'class1' not found in /home/filemobile/testscript/class2.php on line 5

I know this is not proper OOP, but its still a strange error. Normally PHP is pretty good at these weird structures ;). Weirdest thing was that it happened for me on one server, but not the other.

There is a bug marked bogus for this, which is understandable. It would be great though if the PHP could somehow throw an error thats a bit more helpful =P. Its a strange error, especially since I could only reproduce it with this structure, and not with for example just 2 classes with circular dependencies.

 1

About

My name is Evert, and I've been writing semi-regularly on this blog since 2006.

I'm currently available for contract work.

more info.

Subscribe

Dropbox

Dropbox is a simple cross-platform online backup and sync application. The first 2GB of space is free, and both you and me get an extra 250MB extra space if you sign up through this link.