Рассмотрим на примере:
Иерархия:
Код:
foo
|-Foo.php
bar
|-Bar.php
-index.php
Foo.php
Код:
namespace foo;
class Foo
{
public function className()
{
return __CLASS__;
}
}
Bar.php
Код:
namespace bar;
class Bar
{
public function className()
{
return __CLASS__;
}
}
index.php
Код:
spl_autoload_register(function ($class) {
$base_dir = __DIR__;
$file = $base_dir . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';
if (!file_exists($file)) {
throw new \Exception("File is not found: {$file}");
}
require $file;
});
$foo = new \foo\Foo;
$bar = new \bar\Bar;
echo $foo->className(); // display: "foo\Foo"
echo $bar->className(); // display: "bar\Bar"