Search code examples
phpclassspl-autoload-register

spl_autoload_register confusion on require


So I've read some of this PHP function, and I understand how to instantiate it, though I am having difficulties understanding the use case and possibly the functionality of the spl_autoload_register function. So here is what I have

<?php
spl_autoload_register(function($class){
    require_once "classes/{$class}.php";
});

But my question is if my classes directory looks like this

-Security.php
-Zipper.php
-Functions.php
-Sanitize.php
-Extract.php

And if my page does not need every single one of these does it actually require the classes? Or does it only require when it is called like so

new Zipper;

Please help me to clarify this confusion of the spl_autoload_register function. Also does naming conventions work? Say if I try instantiating new Hashing; and that belongs to Security.php how exactly would it know how to require that file, or like I said does naming conventions help?

Example

<?php
spl_autoload_register(function($class){
    switch($class) {
      case "Booger":
      case "booger": $class = "Snot";
    }
    require_once "classes/{$class}.php";
});

Solution

  • spl_autoload_register will only allow the class to possibly be available instead of erroring out -- it doesn't actually instantiate the class.

    What you do in the callback is up to you. Your "Security.php" class file should look something like:

    class Security {
      [...]
    }
    

    Whatever file you include, such as require_once "classes/{$class}.php"; means that the file name AND class name in the file must match $class.