Autoloading headache

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
einarb
Forum Newbie
Posts: 1
Joined: Fri Nov 12, 2010 8:30 am

Autoloading headache

Post 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?
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Autoloading headache

Post 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).
Post Reply