David Barnes David Barnes - 5 months ago 11
PHP Question

How do I use PHP namespaces with autoload?

I get this error when I try to use autoload and namespaces:


Fatal error: Class 'Class1' not found in /usr/local/www/apache22/data/public/php5.3/test.php on line 10


Can anyone tell me what I am doing wrong?

Here is my code:

Class1.php:

<?php

namespace Person\Barnes\David
{
class Class1
{
public function __construct()
{
echo __CLASS__;
}
}
}

?>


test.php:

<?php

function __autoload($class)
{
require $class . '.php';
}

use Person\Barnes\David;

$class = new Class1();

?>

Answer

Class1 is not in the global scope.

See below for a working example:

<?php

function __autoload($class)
{
    $parts = explode('\\', $class);
    require end($parts) . '.php';
}

use Person\Barnes\David as MyPerson;

$class = new MyPerson\Class1();

Edit (2009-12-14):

Just to clarify, my usage of "use ... as" was to simplify the example.

The alternative was the following:

use Person\Barnes\David;

$class = new Person\Barnes\David\Class1();