20
class Manage { spl_autoload_register(function($class) { include $class . '.class.php'; }); } 

Say I have some code like the above. I chose to use the anonymous function method of loading classes, but how is this used? How exactly does it determine which '$class' to load?

4
  • You code is wrong. Either put sql_autoload_register out of class Manage or put it in a method. Commented Jun 21, 2012 at 3:52
  • 2
    @zerkms What is it with OP's and their foul mouths today? And why are they always attacking the mods? Commented Jun 21, 2012 at 3:55
  • 1
    First thing you should do is to syntax-error-check your code before posting it here. Commented Jun 21, 2012 at 7:42
  • Here's a good tutorial demonstrating how to implement spl_autoload_register in your project for class autoloading. Commented Sep 5, 2014 at 2:25

2 Answers 2

28

You can't put the code there. You should add the SPL register after your class. If you wanted to register a function inside the Manage class you could do:

class Manage { public static function autoload($class) { include $class . '.class.php'; } } spl_autoload_register(array('Manage', 'autoload')); 

However, as you demonstrated you can use an anonymous function. You don't even need a class, so you can just do:

spl_autoload_register(function($class) { include $class . '.class.php'; }); 

Either way, the function you specify is added to a pool of functions that are responsible for autoloading. Your function is appended to this list (so if there were any in the list already, yours will be last). With this, when you do something like this:

UnloadedClass::someFunc('stuff'); 

PHP will realize that UnloadedClass hasn't been declared yet. It will then iterate through the SPL autoload function list. It will call each function with one argument: 'UnloadedClass'. Then after each function is called, it checks if the class exists yet. If it doesn't it continues until it reaches the end of the list. If the class is never loaded, you will get a fatal error telling you that the class doesn't exist.

Sign up to request clarification or add additional context in comments.

Comments

15

How exactly does it determine which '$class' to load?

The $class is passed by php automatically. And it's the name of the class not declared yet, but used somewhere in runtime

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.