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("\\","https://stackoverflow.com/",__NAMESPACE__);
    $className=str_replace("\\","https://stackoverflow.com/",$className);
    $class=CORE_PATH."/classes/".(empty($namespace)?"":$namespace."https://stackoverflow.com/")."{$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!";
        }
    }
}
?>

Leave a Comment