This is a personal brief introduction to the Spl_autoload_register () function, the need for students to refer to, mainly to discuss the function of the Spl_autoload_register () function of the parameters of the functions of the individual a bit confused.
Needless to say, on the code, but also ask the students to pay attention to the comments.
<?PHP//defines a function that automatically loads class files functionAutoLoad$class){ //parameter $class, regardless of it, it will be "class name" as the parameter//class file address, the format of the class file is $class.class.php $classPath=Str_replace(' \ \ ', '/', __dir__). ' /‘.$class.‘. Class.php '; //Var_dump ($classPath); if(file_exists($classPath)){ include_once $classPath; } } //register the Auto-load function, at this point autoload this function is equivalent to the automatic search for PHP class function __autoload ()Spl_autoload_register (' AutoLoad '); $obj=NewAuto//This class already exists in the sibling directory, and my case $obj-autoloader (); /*Spl_autoload_register if used in a class, the passed argument must contain the class name and the method name * As in the following example:*/ classloadclass{ Public functionLoadfunction ($class){ $classPath=Str_replace(' \ \ ', '/', __dir__). ' /‘.$class.‘. Class.php '; if(file_exists($classPath)){ include_once $classPath; } } Public function_register () {//registering the Auto-load method loadfunctionSpl_autoload_register (' Self::loadfunction '); //or a parameter is an array, the first element of the arrays is the class name, the second is the method name to registerSpl_autoload_register (Array(' LoadClass ', ' loadfunction ')); } }
Personal experience with parameters:
about the parameters of this function, it bothered me for one hours, you think, Spl_autoload_register () register the function, it is an automatic loading function,we do not need to call it directly, it will automatically load into the stack area,cannot be called directly, that is, we do not need to call the above AutoLoad (), there is no way to pass parameters to it, then where does this parameter come from? This really bothered me for a while when I first met Spl_autoload_register () ,However, I did some experiments and found that this parameter does not need to be passed,it will pass through the name of the class you call, and what class you instantiate,He passed what kind of name, is so intelligent. speaking of which, exclamation spl_autoload_register registration function is bad? Oh, don't believe, you can do the experiment
A little personal insight into PHP's spl_autoload_register function