【问题标题】:__autoload is not executing in PHP__autoload 未在 PHP 中执行
【发布时间】:2011-08-08 23:30:07
【问题描述】:

所以我正在尝试在 PHP 中自动加载类;但是,__autoload() 函数似乎没有执行。即使我尝试echoing $class_name 变量,除了我在下面提供的输出之外,我什么也没看到。我已经包含了所有相关文件并删除了其中不相关的部分。根据PHP: Autoloading Classes - Manual 中的注释,我不能在 CLI interactive mode 中使用 __autoload(),我没有使用它。任何指针将不胜感激。谢谢。

index.php 的输出:

致命错误:在 /home1/tylercro/public_html/cb-test/index.php 的第 3行中找不到类“日历” >

index.php:

<?php
    require_once($_SERVER['INCLUDES'] . 'prep.php');
    $smarty -> assign('calendar', new Calendar());
?>

prep.php:

<?php
    error_reporting(-1);

    function __autoload($class_name) {
        include($_SERVER['CLASSES'] . $class_name . '.php');
    }
    require_once($_SERVER['SMARTY_BIN'] . 'Smarty.class.php');

    $smarty = new Smarty();
?>

.htaccess:

Options -Indexes

SetEnv CLASSES /home1/tylercro/public_html/cb-test/includes/classes/
SetEnv INCLUDES /home1/tylercro/public_html/cb-test/includes/
SetEnv SMARTY_BIN /home1/tylercro/smarty/

【问题讨论】:

  • 始终尝试在不使用 .htaccess 的情况下构建您的应用程序 - 它会帮助您迁移到 nginx。
  • 由于该站点正在积极开发中,因此文件会四处移动。关于如何以尽可能少(或以某种方式减少?)潜在的需要维护来实现相同的行为,您有任何替代建议吗?
  • 好吧,绝对不应该使用在某处声明的“魔术”$_SERVER 常量来完成自动加载。阅读这篇关于使用命名空间和类名的standard,您会在其中找到自动加载的示例。

标签: php autoload


【解决方案1】:

Smarty 有自己的自动加载功能,它会和你的碰撞。 spl_autoload_register() 可以解决您的问题,因为它可以将任何功能注册为自动加载器。

【讨论】:

  • 我查看了让我感到困惑的文档。我不太确定如何使用该功能? spl_autoload() 是什么?
  • 我在将__autoload() 函数重命名为my_autoload() 后注册了它,但现在我收到一些Smarty 文件的警告,我认为这些文件将使用Smarty 的自动加载功能自动加载。顺便说一句,不应该重新声明__autoload() 发出警告或错误吗?为什么我之前没有收到该错误?
  • 我想提一下它自动加载了 Calendar 类会很有帮助。
【解决方案2】:

post 解决了我的问题。我所要做的就是将 prep.php 更改为以下内容:

<?php
    error_reporting(-1);

    function __autoload($class_name) {
        include($_SERVER['CLASSES'] . $class_name . '.php');
    }
    define('SMARTY_SPL_AUTOLOAD',1);
    require_once($_SERVER['SMARTY_BIN'] . 'Smarty.class.php');
    spl_autoload_register('__autoload');

    $smarty = new Smarty();
?>

【讨论】:

  • define('SMARTY_SPL_AUTOLOAD',0);为我做 - Smarty-3.1.2
猜你喜欢
  • 1970-01-01
  • 2020-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-08
  • 1970-01-01
  • 2014-09-28
  • 2012-10-25
相关资源
最近更新 更多