PHP:__autoload函数从未被调用

3

所以,我有xampp。我在ZendServer上测试了这段代码,结果相同。

<?php
error_reporting(E_ALL);

define ("ABS_PATH", 'C:\xampp\htdocs\oopHotLine\\');

function __autoload($class_name) {
    echo 'gg';
    require_once (ABS_PATH.'classes\\'.$class_name.'.php');
}

$process=new Main('1');
?>

在执行 php.exe -a index.php 后,我得到了以下结果:

Interactive mode enabled
Fatal error: Class 'Main' not found in C:\xampp\htdocs\oopHotLine\index.php on line 10
[Finished]

所以,它不显示“gg”的输出。如果我手动执行__autoload('Main'),一切都正常。手动require_once或include也是如此。所有在Windows文件夹中的权限均设置为完全访问。Php版本- PHP版本=>5.3.8;
请帮忙。

你确定文件名叫这个吗? - Wesley
当你使用spl_autoload_register加载像下面这样的自定义函数时,它是否可以工作? - Wesley
是的,我非常确定,即使不是这样 - 在出现错误之前,它不应该首先显示“gg”吗? - NiPh
使用spl_autoload_register的自定义加载器具有相同的输出。 - NiPh
3个回答

2
正如DaveRandom所指出的那样:
Autoloading is not available if using PHP in CLI interactive mode.

所以,不要使用php.exe -a index.php命令,去掉-a,改用php.exe index.php命令来运行脚本。


0

以下是与此主题相关的PHP手册中的笔记:

根据记录的第一条信息,这可能就是答案:

如果在使用PHP CLI交互模式,则无法使用自动加载。

但同时也需要注意以下内容:

spl_autoload_register()为自动加载类提供了更灵活的替代方案。因此,不建议使用__autoload(),并且将来可能会作废或删除。

除此之外,以下是我编写自动加载函数的方法:

function __autoload($class_name) {
  if (file_exists(ABS_PATH."classes/$class_name.php")) { // At least check the file exists before you require it!
    // Forward slashes work on Windows too (in PHP at least)... and they make it more portable
    require_once (ABS_PATH."classes/$class_name.php");
  }
}

<?php error_reporting(E_ALL); define ("ABS_PATH", 'C:/xampp/htdocs/oopHotLine/'); function autoload ($class_name) { echo 'gg'; if (file_exists(ABS_PATH."classes/".$class_name.".php")) { require_once (ABS_PATH.'classes/'.$class_name.'.php'); } } spl_autoload_register ('autoload'); $process=new Main('1'); ?> 该段代码输出相同的结果,对于格式不当表示抱歉。 - NiPh
@NiPh 我真的认为这更多与“如果在CLI交互模式下使用PHP,则无法使用自动加载”有关... - DaveRandom
感谢您对未来__autoload弃用的帮助和信息。 - NiPh

0

http://www.php.net/manual/en/function.spl-autoload-register.php

如果您的代码已经有了一个现有的__autoload函数,那么这个函数必须在__autoload堆栈上显式注册。这是因为spl_autoload_register()将有效地用spl_autoload()或spl_autoload_call()替换__autoload函数的引擎缓存。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接