在子文件夹中使用spl_Autoload_寄存器自动加载PHP
我的目录结构如下所示在子文件夹中使用spl_Autoload_寄存器自动加载PHP,php,namespaces,spl,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 =
> 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
?>
我已经设置了正确的名称空间(仅在类中),并且在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();
?>
到目前为止,它工作得非常完美,它呈现模板并填充模板变量
但当我在admin文件夹中打开索引文件时,它给出了以下错误
致命错误:在中找不到类“classes\template\u vars”
/home/aamir/www/CMS/classes/template.php,第47行
你知道怎么修理这个东西吗。它在根目录下工作,但在管理面板内部它不工作为此,您必须使用一个技巧:
set_include_path(get_include_path() . PATH_SEPARATOR . '../');
在包含。/config.php
或之前
set_include_path(get_include_path() . PATH_SEPARATOR . __DIR__ . '/');
在config.php
中,我遇到了同样的问题(在windows上),我想我可以解释这一问题
例如,让我们看两个简单的脚本,第一个脚本在名为root
的目录中创建一个名为root
的命名空间中的类:
-root\sampleClass.php
:
namespace root;
class sampleClass
{
public function __construct()
{
echo __CLASS__;
}
public function getNameSpace()
{
return __NAMESPACE__;
}
}
第二个脚本位于这里root\index.php
,只包含这两行:
spl_autoload_register();
$o = new sampleClass;
然后,如果运行root\index.php
脚本,将出现如下致命错误:
( ! ) SCREAM: Error suppression ignored for
( ! ) Fatal error: spl_autoload(): Class sampleClass could not be loaded in C:\wamp\www\root\test.php on line 4
如果删除root\sampleClass.php
上的namespace关键字,错误就会消失
因此,我不会对核心php的风度作任何总结,因为我不是php核心开发人员,但会发生类似的事情:
如果不指定名称空间,spl_autoload_register()
函数还将查找当前目录(即root\
),并找到名为sampleClass.php
的类,但如果在我们的示例中指定一个类似root
的命名空间,则为spl_autoload_register()代码>函数将尝试加载位于“root\root”之类位置的文件
因此,现在有两种解决方案:
1)首先不合适的做法是创建一个名为root
的子目录,该子目录还包含sampleClass.php
2)第二个更好的方法是在index.php
脚本中添加一种技巧:
set_include_path(get_include_path().PATH_SEPARATOR.realpath('..'));
这将告诉spl\u autoload\u register()
函数检入父目录
就这些了谢谢你的提示,我在config.php中添加了set\u include\u path
,因为我不想编辑100多个文件,现在它可以正常工作了。谢谢,是的,在config.php
中使用\uuuu DIR\uuuu
也可以做到:)这段代码在我阅读时会伤害我。