我了解如何注册自动加载器,甚至了解如何创建自动加载器,这根本不是问题。主要问题是 - 你如何让两个自动装载机并排运行,例如:
class project_one_folder_class extends project_two_folder_class{}
您会注意到子类属于一个项目,该项目正在调用位于不同项目中的父类。
自动加载器始终可以看到项目链接项目二的类的方式,但从未见过项目的类。
所以我想解决这个问题的方法是编写两个自动加载器并注册它们,因为 php 会查看另一个。 php 似乎只查看一个而不是另一个。
你会如何解决这个问题?
编辑
项目二是父项目,项目一是子项目。这是比 What was posted on this question 更广泛的问题.
为了更好地扩展这是我的类(class)。
class AisisCore_Loader_AutoLoader{
protected static $_instance;
public function get_instance(){
if(null == self::$_instance){
self::$_instance = new self();
}
return self::$_instance;
}
public function reset_instance(){
self::$_instance = null;
}
public function register_auto_loader(){
spl_autoload_register(array($this, 'load_class'));
spl_autoload_register(array($this, 'load_child_class'));
}
public function load_class($class){
$path = str_replace('_', '/', $class);
if(file_exists(get_template_directory() . '/' . $path . '.php')){
require_once(get_template_directory() . '/' . $path . '.php');
}
}
public function load_child_class($class){
$path = str_replace('_', '/', $class);
if(file_exists(get_stylesheet_directory() . '/' . $path . '.php')){
require_once(get_stylesheet_directory() . '/' . $path . '.php');
}
}
}
目前这个类将加载父项目中的任何内容。它甚至会在子项目中加载父项目对象。如何使用此类无法加载子对象,因为它找不到。
那些熟悉 WordPress 的人会立即说,是的,因为你有
get_template_directory
当你想要时 get_stylesheet_directory
如何 - 知道这一点 - 我想写两个自动加载器,一个将使用 get_stylesheet_directory
加载子项目对象然后通过 get_stylesheet_directory
加载父对象以便:class project_one_folder_class extends project_two_folder_class{}
工作和加载,没有错误。
最佳答案
这有点粗糙,但实际上您只需要一个自动加载器,它只在多个目录中进行检查:
abstract class Hakre_Theme_AutoLoader
{
public static $directories;
public static function init()
{
// configure paths
self::$directories = array(
get_template_directory(), // current theme, parent in case of childtheme
get_stylesheet_directory(), // current theme, child in case of childtheme
);
// please double check if you really need to prepend
return spl_autoload_register('Hakre_Theme_AutoLoader::autoload', true, true);
}
public static function autoload($class)
{
$filename = str_replace('_', '/', $class) . '.php';
foreach (self::$directories as $directory) {
$path = $directory . '/' . $filename;
if (is_file($path)) {
require($path);
return; # leave because the class has been loaded
}
}
}
}
Hakre_Theme_AutoLoader::init();
## If you're unsure all worked out properly:
var_dump(Hakre_Theme_AutoLoader::$directories);
这实际上应该可以做到,但是我还没有测试过。见
var_dump
, 您可以调试是否注册了正确的目录。不需要有多个回调只是因为你想 checkin 两个目录。
关于php - PHP 中的自动加载器 - 一次运行两个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15534211/