【问题标题】:php __autoload() is not workingphp __autoload() 不工作
【发布时间】:2014-07-14 17:33:19
【问题描述】:

我没有在我的文件中看到任何错误,但是当我运行我的代码时,它会显示以下错误:

警告:require_once(Core.php):打开流失败:第 7 行的 C:\xampp\htdocs\completed\inc\autoload.php 中没有这样的文件或目录

致命错误:require_once():在 C:\xampp\htdocs\completed\inc\autoload.php 中打开所需的 'Core.php' (include_path='.;C:\xampp\php\PEAR') 失败第 7 行

我的代码是:

classes/Core.php

 <?php
  class Core {

   public function run() {
      ob_start();
      require_once(Url::getPage());
      ob_get_flush();
     }

}

inc/autoload.php

 <?php
 require_once('config.php');

function __autoload($class_name) {
   $class = explode("_", $class_name);
   $path = implode("/", $class).".php";
   require_once($path);
}

index.php

<?php
require_once('inc/autoload.php');
$core = new Core();
$core->run();

【问题讨论】:

  • 这些类存在于classes 文件夹下,但您正试图从当前目录中包含。
  • 我在我使用 set_include_path() 函数的 inc 文件夹下创建了一个 config.php 文件,我首先在 autoload.php 文件中调用它,所以不需要识别我认为它自动识别的类文件夹
  • 错误显示所有包含目录的列表。显然,该列表中不包括classes。您是否在所有这些运行之前加载配置文件?
  • checked.i 包括类文件夹
  • 这是您在提问后添加的内容吗?我问是因为错误特别指出include_path='.;C:\xampp\php\PEAR'。我在那里看不到classes。如果错误已更改,也许您应该更新错误。

标签: php


【解决方案1】:

我知道有点晚了。我正在研究这个,因为我有同样的问题。这是我尝试过的,它对我有用。

// 此代码用于 inc/autoload.php 文件。

define('__ROOT__', dirname(dirname(__FILE__)));
require_once(dirname(__FILE__) . "/config.php");

//require_once(inc/config.php);


function __autoload($className){
$class = explode("_",$className);
$path = implode("/",$class).".php";
require_once($path);    

}

请我刚开始学习 PHP,我会得到你们的纠正。 我希望这有帮助。

【讨论】:

    【解决方案2】:

    您的 Core 类显然定义在:

    C:\xampp\htdocs\completed\classes\Core.php
    

    但您尝试加载此文件:

    C:\xampp\htdocs\completed\Core.php
    

    构建一个使用相对路径的类自动加载器不是一个好主意*。我建议你在这里添加一个前缀来构建一个绝对路径:

     $path = implode("/", $class).".php";
    

    例如:

     $path = __DIR__ . '/../classes/' . implode("/", $class).".php";
    

     


    (*) 除其他原因外,因为 PHP 中的相对路径是相对于 main 脚本(而不是发生路径使用时的文件),所以源目录取决于您使用的脚本加载autoload.php from。

    【讨论】:

      【解决方案3】:

      你的问题我也遇到过。我想你已经晚了。但可能对其他人有帮助。

      没有在 autoload.php 文件中包含 config.php 文件

      inc/autoload.php

      //require_once('config.php');
      

      在 index.php 中包含了 config.php 文件,如下所示:

      index.php

      require_once('inc/config.php');
      require_once('inc/autoload.php');
      

      它对我有用,我希望这对你也有用:)。感谢您花时间阅读我的评论。

      【讨论】:

        【解决方案4】:

        因为在同一个文件夹中

        require_once('inc/autoload.php');
        
        require_once('config.php');
        

        所以..我觉得应该是这样的

        require_once('inc/config.php');
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-09-28
          • 2011-04-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多