Hi All,

I'm having trouble understanding how the spl_autload (and namespaces) should be implemented. I have the following:

namespace A\Core;

class Controller {

}

extended by:

class SiteController extends \A\Core\Controller {

    public function __construct() {
        echo 'Created SiteController!';
    }
}
  • I'm not sure if this is the correct/best way to get the class without loading the entire namespace.

The autoload class being loaded with spl_autoload_register(array($this,'autload'):

private function autoload($className){

        if(($pos=strrpos($className,'\\'))!==false){
            $className=substr($className,$pos+1);
        }

        if(isset(self::$_coreClasses[$className])){
            require(dirname(__FILE__).self::$_coreClasses[$className]);
        }elseif(strstr($className,'Controller')){
            if(in_array($className.'.php',scandir(self::$_basePath.DIRECTORY_SEPARATOR.'controllers'))){
                require(self::$_basePath.DIRECTORY_SEPARATOR.'controllers'.DIRECTORY_SEPARATOR.$className.'.php');
            }
        }
    }

So, here I'm trying to see if a namespace occurs and then I'm getting the class from the $className string. It calls the SiteController via the elseif but then doesn't come back around for its parent ('Controller'). It doesn't even try call spl_autoload_call().
The 'Controller' class is in the $_coreClasses so when processed should not encounter the elseif. Though it doesm't seem to be getting that far anyway.

The stack:

1   0.0000  241480  {main}( )   ..\index.php:0
2   0.0000  281984  A\A::createApplication( )   ..\index.php:13
3   0.0000  284272  A\A->readUrl( ) ..\A.php:43
4   0.0000  285000  A\A->getController( )   ..\A.php:116
5   0.0000  285528  spl_autoload_call ( )   ..\A.php:125
6   0.0000  285744  A\A->autoload( )    ..\A.php:0
7   0.0000  288832  require( 'absolute\path\to\controllers\SiteController.php' )    ..\A.php:93

As you can see, it stops looking for the parent class once it includes the SiteController, giving me the error:

Fatal error: Class 'A\Core\Controller' not found in absolute\path\to\controllers\SiteController.php on line 3

Any help/direction here would be greatly appreciated. Thanks.

changed autload function to:

private function autoload($className){

        if(($pos=strrpos($className,'\\'))!==false){
            $className=substr($className,$pos+1);
        }

        foreach(self::$_classPaths as $path){
            $classFile = $path.DIRECTORY_SEPARATOR.$className.'.php';
            if(is_file($classFile)){
                require($classFile);
            }
        }
    }

all works now. As far as I can tell.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.