Search code examples
phplaravelspl-autoload-register

How do the spl_autoload_register do with array not function name?


In Laravel's AliasLoader, it will register to spl_autoload_register like this:

spl_autoload_register([$this, 'load'], true, true);

What does spl_autoload_register do with the array [$this, 'load']?


Solution

  • The first argument of spl_autoload_register is a callable, as explained in the documentation.

    The documentation for the callabletype says:

    A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1. Accessing protected and private methods from within a class is allowed.

    In the case for your question, [$this, 'load'] refers to the method load() on the same class where spl_autoload_register is called.

    E.g. something like this:

    class Foo {
    
      public function register() {
    
         spl_autoload_register([$this, 'load'], true, true);
      }
    
      public function load($className) {
         // do your loading
      }
    }
    
    $autoloader = new Foo();
    $autoloader->register();