index.php在root

时间:2018-02-10 17:02:44

标签: php namespaces root spl-autoload-register

使用现代PHP,调用

spl_autoload_register();

允许您实例化新类,而不必在php文件中指定REQUIRE,INCLUDE和USE,只要它们具有命名空间,并且只要该命名空间遵循文件夹/文件结构,例如:

|--models
     |-- utility
|           |___calculator.php
|
|
|--index.php

使用这样的设置,如果calculator.php已在其顶部"命名空间models \ utility"中声明,并且它包含类Calculator(与文件名calculator.php匹配),您可以自动实例化它来自index.php,致电:

calc = New models\utility\Calculator();

但是,如果文件夹结构如下:

|--models
     |-- utility
|           |___calculator.php
|
|
|--public
     |--index.php

现在index.php无法再通过其命名空间访问计算器,因为index.php不再位于根文件夹中。

似乎public / index.php无法达到其级别以上的命名空间。这只是PHP的一个限制。是否有一种方法可以使用spl_autoload_register注册一个函数,该函数将保留其自动,易于使用的行为,但允许index.php在其文件夹级别上实例化名称空间?或者另一种处理这种情况的方法,但仍然不必使用或请求/包含文件?

更新答案

这是一个对我有用的目录无关解决方案。我只能通过调用它们的命名空间来成功实例化新类,而不必依赖于USE,REQUIRE或INCLUDE即使index.php被移动到/ public文件夹。

//'/../../../../' points the autoloader.php file back to root directory
$include_path = realpath(dirname(__FILE__) . '/../../../../');         
set_include_path($include_path);
spl_autoload_register();

1 个答案:

答案 0 :(得分:3)

如果在没有$autoload_function参数的情况下调用spl_autoload_register()函数,则使用默认的自动加载函数spl_autoload()

spl_autoload()函数检查文件的所有include paths,将名称空间与文件夹和类名匹配,如同您已经注意到的那样。

您的关键是确保包含类文件的目录结构的文件夹(即包含models的目录)位于包含路径中。这通常使用set_include_path()函数来完成。