PHP namespace autoload -
trying understand how namespaces , autoload works on php
server.php located @ 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 subtopic; $test = new subtopic\main(); var_dump($test);
it cant load class core/server/main
autoload doesn't work way. first explain how autoloaders works.
spl_autoload_register() function register function have in code server autoloader, standard function 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 path directory code lives. noticed param passed spl_autoload_register name of function, register function when class instanciated runs function.
now effective way use autoloaders , namespaces 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 , autoload load functions in nicely way, can use namespace describe in dir class resides , uses autoloader magic load without problems.
note: used constant 'ds', because in *nix uses '/' , in windows uses '\', directory_separator don't have worry code going run, because "path-compatible"
Comments
Post a Comment