How do I use PHP namespaces with autoload?

Class1 is not in the global scope.

Note that this is an old answer and things have changed since the days where you couldn’t assume the support for spl_autoload_register() which was introduced in PHP 5.1 (now many years ago!).

These days, you would likely be using Composer. Under the hood, this would be something along the lines of this snippet to enable class autoloading.

spl_autoload_register(function ($class) {
    // Adapt this depending on your directory structure
    $parts = explode('\\', $class);
    include end($parts) . '.php';
});

For completeness, here is the old answer:

To load a class that is not defined in the global scope, you need to use an autoloader.

<?php

// Note that `__autoload()` is removed as of PHP 8 in favour of 
// `spl_autoload_register()`, see above
function __autoload($class)
{
    // Adapt this depending on your directory structure
    $parts = explode('\\', $class);
    require end($parts) . '.php';
}

use Person\Barnes\David as MyPerson;

$class = new MyPerson\Class1();

or without aliases:

use Person\Barnes\David\Class1;

$class = new Class1();

Leave a Comment