Reputation: 2412
I´m having a hard time trying to autoload parent classes
this is my directory structure
controllers
--- Homepage.php
core
--- Controller.php
index.php
This is the content of my index.php
function __autoload($class_name)
{
$file_name = str_replace("\\", DIRECTORY_SEPARATOR, $class_name) . '.php';
include $file_name;
}
$homepage = new \Controllers\Homepage();
$homepage->index();
This is the content of my controllers/Homepage.php file
namespace Controllers;
class Homepage extends Controller
{
public function index()
{
echo 'Homepage::index';
}
}
and this is my core/Controller.php
namespace Core;
class Controller
{
protected function something()
{
echo 'blablabla';
}
}
when i run index.php the autoloader loads Hompege correctly but is looking for Controller.php in the controllers directory I tried extending from class Homepage extends Core\Controller but now is trying to get it from controllers/core
Upvotes: 1
Views: 826
Reputation: 24551
This is how the namespaces are resolved:
class Homepage extends Controller
Controller
is resolved to Controller\Controller
because it is a non-qualified class name (like a relative file path), and the current namespace is used.
class Homepage extends Core\Controller
Core/Controller
is resolved to Controller\Core\Controller
because it also is a non-qualified class name and a sub-namespace of the current namespace is used
class Homepage extends \Core\Controller
\Core\Controller
is a fully qualified class name and will be resolved to Core\Controller
use Core\Controller; class Homepage extends Controller
Here the use
statement specifies that a non-qualified Controller
is treated as Core\Controller
Variants 3 and 4 will work as intended.
Upvotes: 1