2014-04-30 64 views
1

我有一个PHP自动加载类的问题。PHP:autoload类没有找到

在我index.php我写(这是一个simpliest):

function _autoload($class_name) { 
    require_once $class_name . '.php'; 
} 

$a = new Cont(); 

Cont.php文件位于PROJECT_ROOT/assets/core/Contr.php;

结果我index.php文件会抛出一个致命的错误:

Fatal error: Class 'Cont' not found in /var/www/bill/index.php on line 15 

回答

3

应该__autoload()好像你错过了一个下划线。

也就是说..

function __autoload($class_name) { 
    require_once $class_name . '.php'; 
} 

$a = new Cont(); 

小费从PHP Manual...

spl_autoload_register() provides a more flexible alternative for autoloading classes. For this reason, using __autoload() is discouraged and may be deprecated or removed in the future.

1

首先,它是__autoload - 两个下划线。

其次,该技术不鼓励 - spl_autoload_register是一个更好的选择。

第三,如果您的文件在PROJECT_ROOT/assets/core中,则可能需要require_once 'assets/core/' . $class_name . '.php';

+0

是的。谢谢你一个愚蠢的错误 - 没有发现一个缺少的下划线。 –