2012-05-07 132 views
2

我的目录结构spl_autoload_register是类似下面PHP自动加载与子文件夹

> 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(); 
?> 

到目前为止它是工作完美的,它呈现的温度末和填充模板增值经销商,

,但是当我在管理文件夹中打开索引文件,它提供了以下错误

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

任何想法如何解决这件事情。它适用于根,而是从管理面板中它亘古不变的工作

+0

不知何故,当我阅读它时,这段代码伤害了我。 – hakre

回答

2

你必须使用一个技巧:

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

之前包括../config.phpOR

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

config.php

+0

感谢您的提示,我已经在config.php中添加了'set_include_path',因为我不想编辑100多个文件,现在它工作正常。 THANKX –

+0

啊,是的,在'config.php'内使用'__DIR__'也可以做到这一点:) –

2

我面临同样的问题(在Windows上),我想我可以解释这件事。

例如,让我们两个简单的脚本,第一个创建的namespaceroot在DIR一类叫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_autoload_register()函数检查父目录。

这就是全部