phpnamespacesspl-autoloader

PHP autoloaders and namespaces


I'm slightly confused by autoloaders and namespaces in PHP.

My classes are organised within an assets file,

-- Assets
    -- user
       -- User.php
    -- database
       -- Database.php

This is just a simple version, there are more files in each folder (i.e. user, database).

There is no need to worry about conflicting vendor names as there is only one vendor in this project (i.e. me) but for example, using the PSR0 autoloader:

function autoload($className)
{
    $className = ltrim($className, '\\');
    $fileName  = '';
    $namespace = '';
    if ($lastNsPos = strripos($className, '\\')) {
        $namespace = substr($className, 0, $lastNsPos);
        $className = substr($className, $lastNsPos + 1);
        $fileName  = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
    }
    $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';

    require $fileName;
}

Do I need to declare a namespace in each of my class files and initilize a class by using new user\User();. Is it not possible to initilize it by using new user_User;

Many thanks


Solution

  • The PSR-0 autoloader convention doesn't require you to use namespaces that map to your directory structure. You can also use underscores in the class name for basically the same purpose.

    Like the \ namespace separator, any underscores in the class name are converted to DIRECTORY_SEPARATOR when looking up the file to load. So, a class user_User and \user\User would both result in the autoloader looking for the same file: user/User.php.