PHP命名空间自动加载


PHP namespace autoload

试图了解名称空间和自动加载如何在PHP 上工作

Server.php位于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;
        }
     }
}

和Index.php

spl_autoload_register();
use core'server as subtopic;
$test = new subtopic'Main();
var_dump($test);

它无法加载类core/server/Main

自动加载不能以这种方式工作。首先,我将解释自动加载器是如何工作的。

spl_autoload_register((是一个函数,用于将代码中的函数注册为自动加载器,标准函数为:

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');

常量APP_PATH将是代码所在目录的路径。正如您所注意到的,传递给spl_autoload_register的参数是我的函数的名称,它注册函数,这样当一个类被实例化时,它就会运行该函数。

现在,使用自动加载器和名称空间的有效方法如下:

文件-/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');

文件-/index.php

include 'autoloader.php';
$tree = new Libs'Tree();
$apple_tree = new Libs'Tree'AppleTree();

文件-/Libs/Tree.php

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

文件-/Libs/Tree/AppleTree.php

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

我使用名称空间和自动加载来很好地加载我的函数,你可以使用名称空间来描述你的类所在的目录,并使用自动加载魔法来加载它,而不会有任何问题。

注意:我使用了常量"DS",因为在*nix中它使用了"/",在Windows中它使用"''",使用DIRECTORY_SEPARATOR,我们不必担心代码将在哪里运行,因为它将是"路径兼容"的