SPL autoloader class auto creating new objects

682 Views Asked by At

I am going to invoke creating new objects, via SPL autoloader. But i couldnt create new object of class which was already included by loader. Dunno why, but i dont want to use eval, where i can find answer? Sorry for my bad english..

nothing strange simple code:

class load
{  public static function init()
    {return spl_autoload_register(array(__CLASS__, "hook"));}
    public static function quit()
    {return spl_autoload_unregister(array(__CLASS__, "hook"));}
    public static function hook($class)
    {   echo "CLASS IS:$class<br>";
        $lnk=PATH . str_replace("_", "/", $class) . ".php";
        ob_start();
        require $lnk;

        ob_clean();

    }
}
1

There are 1 best solutions below

2
On

Autoloaders aren't for creating new objects; they're for including new classes. Once the class exists, the autoloader doesn't need to load it again -- in fact, it couldn't without triggering a fatal error (since classes can't be defined twice). Therefore, it won't run the class file that you presumably also coded to have some other side effects.

If you want a new object, just create it with new ClassYouWantToCreatAnInstanceOf. If the class doesn't exist yet, the autoloader will try to load it. But the class file generally shouldn't be creating instances itself, for the very reason you're seeing.