Page 1 of 1

Autoloading headache

Posted: Fri Nov 12, 2010 8:40 am
by einarb
I stumbled on something regarding the PHP autoloader. If I have the following in a file called A.php:

Code: Select all

function __autoload($class_name) {
    include $class_name . '.php';
}

class Starter extends SubClass {
        function __construct() {
                parent::__construct();
                print "In Starter constructor\n";

        }
}

class SubClass extends ThirdClass {
        function __construct() {
                print "In SubClass constructor\n";
        }
}

$obj  = new Starter();
and then in ThirdClass.php I have:

Code: Select all

class ThirdClass {
        function __construct() {
                print "In ThirdClass constructor\n";
        }
}
I get a PHP Warning: include(): Failed opening 'SubClass.php' for inclusion and PHP Fatal error: Class 'SubClass' not found. If SubClass doesn't extend ThirdClass I get no error. It seems that using the autoloader requires that subclasses be declared after parent classes if they're declared in the same file, something which is not required if not using the autoloader. Can someone confirm and possibly explain this?

Re: Autoloading headache

Posted: Fri Nov 12, 2010 11:08 am
by Weirdan
This was a bug for so long it became a feature. See http://bugs.php.net/bug.php?id=6418

Basically if you define class A inheriting from class B which, in turn, inherits from class C and they all are in the same file, B must come before A (C may come after though).