PHP 在子文件夹中使用 spl_autoload_register 自动加载

Aam*_*ood 4 php spl namespaces

我的目录结构如下所示

> Root
> -Admin // admin area
> --index.php // admin landing page, it includes ../config.php
> -classes // all classes
> ---template.php 
> ---template_vars.php // this file is used inside template.php as $template_vars = new tamplate_vars();
> -templates // all templates in different folder
> --template1
> -index.php
> -config.php
Run Code Online (Sandbox Code Playgroud)

在我使用的 config.php 文件中

<?php
.... // some other php code
spl_autoload_register(NULL, FALSE);
spl_autoload_extensions('.php');
spl_autoload_register();

classes\template::setTemplate('template/template1');
classes\template::setMaster('master');
 .... // some other php code
?>
Run Code Online (Sandbox Code Playgroud)

我已经设置了正确的名称空间(仅在类中),并且在 root 上的 index.php 中我访问了这些类

<?php 

require 'config.php';
$news_array = array('news1', 'news1'); // coming from database

$indexTemplate = new \classes\template('index');
$indexTemplate->news_list = $news_array; // news_list variable inside index template is magically created and is the object of template_vars class
$indexTemplate->render();
?>
Run Code Online (Sandbox Code Playgroud)

到目前为止,它工作完美,它渲染模板并填充模板变量,

但是当我在管理文件夹中打开索引文件时,出现以下错误

致命错误:在第 47 行 /home/aamir/www/CMS/classes/template.php 中找不到类“classes\template_vars”

知道如何解决这个问题。它可以在 root 上运行,但从管理面板内部它不起作用

Ja͢*_*͢ck 5

为此你必须使用一个技巧:

set_include_path(get_include_path() . PATH_SEPARATOR . '../');
Run Code Online (Sandbox Code Playgroud)

在包含../config.php OR之前

set_include_path(get_include_path() . PATH_SEPARATOR . __DIR__ . '/');
Run Code Online (Sandbox Code Playgroud)

里面config.php