I’m trying to implement autoloading in Php5.3 using namespaces but I’m having some issues and don’t know why it’s not working.
I have a basic directory structure of
/root
--bootstrap.php
--test.php
--/src
----/com
------/a
--------Foo.php
------/b
--------Bar.php
bootstrap.php
<?php
function __autoload($class) {
// convert namespace to full file path
echo $class.'<br>';
$class = str_replace('\\', '/', $class) . '.php';
require_once($class);
}
Foo.php
<?php
namespace src\com\a {
class Foo {
public function write() {
echo "write";
}
}
}
Bar.php
<?php
use \src\com\a\Foo;
namespace src\com\b {
class Bar {
public function write() {
$foo = new Foo();
$foo->write();
}
}
}
test.php
<?php
use \src\com\b\Bar;
require_once("bootstrap.php");
$bar = new Bar();
$bar->write();
So the basic premise is call Bar, which in turn includes Foo and calls the write method
output:
src\com\b\Bar
src\com\b\Foo
But when I try and autoload it thinks Foo is in the namespace of src/com/b because that is the namespace of Bar and therefore it doesn’t load.
Any ideas on how to fix this?
It looks like bar.php should be: