Raggaer
Raggaer

Reputation: 3318

PHP namespace autoload

Trying to understand how namespaces and autoload works on PHP

Server.php located at core/server.php

namespace core\server

{
     class Main
     {
        public function getTopic()
        {
            $get_params = $_GET;    
            if (empty($get_params)) $get_params = ['subtopic' => 'test'];   
            return $get_params;
        }
     }
}

and Index.php

spl_autoload_register();

use core\server as subtopic;

$test = new subtopic\Main();

var_dump($test);

It cant load the class core/server/Main

Upvotes: 1

Views: 646

Answers (1)

Ricardo Barros
Ricardo Barros

Reputation: 205

Autoload doesn't work that way. First I will explain how autoloaders works.

spl_autoload_register() is a function to register a function you have in your code to server as an autoloader, the standard function would be:

define('APP_PATH','/path/to/your/dir');

function auto_load($class)
{
    if(file_exists(APP_PATH.$class.'.php'))
    {
        include_once APP_PATH.$class.'.php';
    }
}

spl_autoload_register('auto_load');

The constant APP_PATH would be the path to your directory where your code lives. As you noticed it the param that is passed to spl_autoload_register is the name of my function, this register the function so when a class is instanciated it runs that function.

Now an effective way to use autoloaders and namespaces would be the following:

file - /autoloader.php

define('APP_PATH','/path/to/your/dir');
define('DS', DIRECTORY_SEPARATOR);

function auto_load($class)
{
    $class = str_replace('\\', DS, $class);
    if(file_exists(APP_PATH.$class.'.php'))
    {
        include_once APP_PATH.$class.'.php';
    }
}

spl_autoload_register('auto_load');

file - /index.php

include 'autoloader.php';

$tree = new Libs\Tree();

$apple_tree = new Libs\Tree\AppleTree();

file - /Libs/Tree.php

namespace Libs;
class Tree
{
   public function __construct()
   {
      echo 'Builded '.__CLASS__;
   } 
}

file - /Libs/Tree/AppleTree.php

namespace Libs\Tree;
class AppleTree
{
    public function __construct()
    {
       echo 'Builded '.__CLASS__;
    } 
 }

I'm using namespaces and autoload to load my functions in a nicely way, you can use namespace to describe in what dir your class resides and uses the autoloader magic to load it without any problems.

Note: I used the constant 'DS', because in *nix it uses '/' and in Windows it uses '\', with DIRECTORY_SEPARATOR we don't have to worry where the code is going to run, because it will be "path-compatible"

Upvotes: 2

Related Questions