Reputation: 1841
I think I may be missing something simple here and need a second pair of eyes. This fails with a fatal error class not found. The autoload function was taken from the PSR-0 github page.
<?php
function my_autoload($className)
{
$className = ltrim($className, '\\');
$fileName = '';
$namespace = '';
if ($lastNsPos = strrpos($className, '\\')) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
return $fileName;
}
spl_autoload_register('my_autoload');
new Vendor\Package\Example();
This is my index.php, the Class is located at Vendor/Package/Example.php, here is the contents.
<?php
namespace Vendor\Package;
class Example {
public function __construct() {
echo __CLASS__ . ' Created with Namespace ' . __NAMESPACE__;
}
}
It works when I do this require_once my_autoload('Vendor\Package\Example');
Upvotes: 1
Views: 76
Reputation: 29462
The autoload function was taken from the PSR-0 github page.
No, on the page there is no return $fileName;
but require $fileName;
Upvotes: 4