Search code examples
phpspl-autoload-register

PHP spl_autoload_register class name in a function


I'm trying to do a little learning here by studying. I'm new to this spl_autoload_register. I noticed it's implementation in a plugin and was curious to know how the $class_name variable[parameter] is established. How does the logic work that the $class_name reads the "class name" as it's paramater? Where does that come from. Maybe I'm confused by the actual inclusion of spl_autoload_register, but how exactly does that work? I'm assuming "Classic_Editor" is the first class name? Can this be explained in a more dumbed down way?

// Add the autoloader
spl_autoload_register( 'frm_forms_autoloader' );
//invokes or calls a function when a class is loading : spl_autoload_register 
//calls a function when a class is loaded
//in other words it says when you try to load a class
//"hey computer could you please do this"
//https://www.youtube.com/watch?v=20nFAHJT2Qg
//
//exit(var_dump($class_name));
//var_dump(debug_backtrace());//GREAT RESOURCE AS IT LISTS FILES AS THEY'RE CALLED TO FIND LAST CLASS NAME OR CLASS CALLED?
function frm_forms_autoloader( $class_name ) {
    // Only load Frm classes here
    //exit(var_dump($class_name));//this exits with "Classic_Editor"
    if ( ! preg_match( '/^Frm.+$/', $class_name ) || preg_match( '/^FrmPro.+$/', $class_name ) ) {
        return;
    }

    frm_class_autoloader( $class_name, dirname( __FILE__ ) );
}

Solution

  • I believe it just "clicked" after watching another tutorial. I believe this to be how this works in simple terms:

    <?php
        spl_autoload_register(function($class_name) {
            //$class_name automatically passed into this and the class will be the name of the class as it runs. 
        });
        ?>
        
        $Aclass = new Aclass;//$class_name will be Aclass  
    

    Edit: As per comment for more information. The reference for my answer was found in this Youtube video :

    https://www.youtube.com/watch?v=20nFAHJT2Qg

    It was described as this

    "Calls a function when a class is loaded. In other words, it says to the computer.... (when you try to load a class can you please do this)"

    The important part where I was getting tripped up was that I wasn't recognizing the "$class_name" for what it was. We're using an anonymous function and the argument is the $class_name returned as an argument by the "spl_autoload_register" function as it fires when a class is loaded.