Question

The question asked here is very similar.

I'm trying to write an autoloader to support imported namespaces. My directory structure looks like this (class files are listed):

/includes
     /php
         config.php
         Shapes.php
         Animals.php
/PetsModule
     /classes
         Cat.php
         Dog.php
     pcontroller1.php
     pcontroller2.php
/MathModule
     /classes
         Triangle.php
         Square.php
     mcontroller1.php
     mcontroller2.php

All of my controllers include the config.php file, which has my autoloader code:

<?php

spl_autoload_register(function($fqClassName) {
    $fqClassName = ltrim($fqClassName, '\\');
    $lastSlash = strrpos($fqClassName, '\\');

    if($lastSlash) {
        // The class is in a namespace
        require '/' . str_replace('\\', '/', substr($fqClassName, 0, $lastSlash)) . '/classes/' . substr($fqClassName, $lastSlash + 1) . '.php';
    } else {
        // The class is global
        require "/includes/php/$fqClassName.php";
    }
}, true);

Now this works fine for all basic cases, but it fails when you start importing namespaces. For instance:

<?php

namespace MathModule;

use PetsModule;

$t = new Triangle(60, 60, 60); // works fine
$fluffy = new Cat("Fluffy"); // fails

The fully-qualified class name that gets passed to the autoloader function is MathModule\Cat, which is a fair assumption.

Is there a way to make the autoloader work with imported namespaces? I'm guessing there has to be a way since my autoloader is very similar to the one for PSR-0.

Was it helpful?

Solution

Autoloading does not matter.

To use new Cat("Fluffy") you should write use PetsModule\Cat; or use PetsModule\Cat as Cat;

http://www.php.net/manual/en/language.namespaces.importing.php

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top