Best Way To Autoload Classes In PHP

Please, if you need to autoload classes - use the namespaces and class names conventions with SPL autoload, it will save your time for refactoring. And of course, you will need to instantiate every class as an object. Thank you.

Like in this thread: PHP Autoloading in Namespaces

But if you want a complex workaround, please take a look at Symfony's autoload class: https://github.com/symfony/ClassLoader/blob/master/ClassLoader.php

Or like this (I did it in one of my projects):

<?
spl_autoload_register(function($className)
{
    $namespace=str_replace("\\","/",__NAMESPACE__);
    $className=str_replace("\\","/",$className);
    $class=CORE_PATH."/classes/".(empty($namespace)?"":$namespace."/")."{$className}.class.php";
    include_once($class);
});
?>

and then you can instantiate your class like this:

<?
$example=new NS1\NS2\ExampleClass($exampleConstructParam);
?>

and this is your class (found in /NS1/NS2/ExampleClass.class.php):

<?
namespace NS1\NS2
{
    class Symbols extends \DB\Table
    {
        public function __construct($param)
        {
            echo "hello!";
        }
    }
}
?>

If you have an access to the command line, you can try it with composer in the classMap section with something like this:

{
    "autoload": {
        "classmap": ["yourpath/", "anotherpath/"]
    }
}

then you have a wordpress plugin to enable composer in the wordpress cli : http://wordpress.org/plugins/composer/


function __autoload($class_name) {
   $class_name = strtolower($class_name);
   $path       = "{$class_name}.php";
   if (file_exists($path)) {
       require_once($path);
   } else {
       die("The file {$class_name}.php could not be found!");
   }
}

UPDATE: __autoload() is deprecated as of PHP 7.2


http://php.net/manual/de/function.spl-autoload-register.php

spl_autoload_register(function ($class) {
    @require_once('lib/type/' . $class . '.php');   
    @require_once('lib/size/' . $class . '.php');
});