phpspl-autoloader

PHP: autoload class not found


I have a problem autoloading classes in PHP.

In my index.php I write (that's the simpliest one):

function _autoload($class_name) {
  require_once $class_name . '.php';
}

$a = new Cont();

My Cont.php file is located at PROJECT_ROOT/assets/core/Contr.php;

As a result my index.php file throws a fatal error:

Fatal error: Class 'Cont' not found in /var/www/bill/index.php on line 15

Solution

  • It should be __autoload() seems like you missed an underscore character.

    That is..

    function __autoload($class_name) {
      require_once $class_name . '.php';
    }
    
    $a = new Cont();
    

    A tip from the PHP Manual...

    spl_autoload_register() provides a more flexible alternative for autoloading classes. For this reason, using __autoload() is discouraged and may be deprecated or removed in the future.