【问题标题】:Class not found error, using autoload to use classClass not found 错误,使用自动加载来使用类
【发布时间】:2016-01-05 07:25:37
【问题描述】:

出现错误:

在 C:\wamp\www\New folder\index.php 中找不到类“位置” 线……

项目文件位置:http://localhost/New%20folder/ 这里类文件和索引文件都保存了。

类文件:location.class.php

class location
{
    function add_location()
    {
        echo 'Its working!';
    }
}

我的代码(index.php 根目录下的文件)

<?php
function __autoload($class_name) {
      if (file_exists($class_name . '.class.php')) 
      {
          require_once ($class_name . '.class.php');
      }   
}
try {
    $location = new location();
} catch (Exception $e) {
    echo $e->getMessage(), "\n";
}
?>
<html>
    <head>
        <title>Autoload Testing</title>
    </head>    
    <body>
    </body>
</html>

【问题讨论】:

  • 我尝试了相同的代码及其工作。你用的是什么版本的php?
  • PHP 版本:5.5.12
  • 我使用的是 5.5.11,它工作正常。
  • 哦...我尝试了太多次...但它不起作用。
  • autoload 函数实际上是获取文件...我使用 file_exist 检查文件是否存在于该特定目录中。我也使用 else 块...

标签: php autoload


【解决方案1】:

您错过了 location.class.php 中的开始 php 标签。

<?php

class location
{
    function add_location()
    {
        echo 'Its working!';
    }
}

(结束标签?&gt;在文件末尾是可选的。)

【讨论】:

    【解决方案2】:

    如下更改你的 location.class.php 内容..

    //php打开 函数 __autoload($class_name) { if (file_exists( dirname( __FILE__ ).'/'.$class_name . '.class.php')) { require_once (dirname( __FILE__ ).'/'.$class_name . '.class.php'); } } //php关闭

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-22
      • 1970-01-01
      • 2011-11-06
      • 1970-01-01
      • 1970-01-01
      • 2015-02-12
      • 2023-04-03
      相关资源
      最近更新 更多