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();
?>
Class1is 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.
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.
or without aliases: