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

标签 php namespaces spl

我的目录结构如下

> 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

在我使用过的 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
?>

我已经设置了正确的命名空间(仅在类中),并在我的 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();
?>

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

但是当我在 admin 文件夹中打开索引文件时,它给出了以下错误

Fatal error: Class 'classes\template_vars' not found in /home/aamir/www/CMS/classes/template.php on line 47



知道如何解决这个问题。它适用于 root,但从管理面板内部它不起作用

最佳答案

你必须使用一个技巧:

set_include_path(get_include_path() . PATH_SEPARATOR . '../');

在您包含之前 ../config.php
set_include_path(get_include_path() . PATH_SEPARATOR . __DIR__ . '/');

config.php

关于PHP 在子文件夹中使用 spl_autoload_register 自动加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10479922/

相关文章:

php - 从多个表中选择一个值

python - 在 Python 中,赋值运算符在类方法定义中作为默认值传递时是否访问类或实例变量?

r - 切换和 tabsetPanel 的 Shiny 命名空间问题

PHP COUNT_RECURSIVE 和 SplFixedArray

php - Docker中的Wordpress和mssql-php

PHP SpreadSheet 找不到自动调整列宽的功能

php - 每个帖子后删除按钮(php,sql)

PHP 预定义接口(interface)和 SPL - 版本检查是否足够?

php - SQL/PHP : Show top 3 most sold products from database

c# - 有没有办法让本地 C++ API 和托管 C++\CLI API 包装它具有相同的 namespace 和类名称