dongtang5229 2018-04-07 07:58
浏览 301
已采纳

致命错误:未捕获错误:未找到类“应用程序\数据库”

I try to learn oop but in my first class it gives me this error.

Database class

<?php
namespace App;

class Database
{
   ...
}

in my functions.php

<?php
require 'helpers.php';
require 'connection.php';
use App\Database;
...

Class under the "app" folder and it's namespace is "App". Why I'm getting this error ?

  • 写回答

2条回答 默认 最新

  • douchang8219 2018-04-07 08:05
    关注

    You either need to include the file, or use an AutoLoader. AutoLoaders tell PHP where a class can be found, as PHP needs to know the file.

    Autoloaders are fully explained in the PHP documentation: https://secure.php.net/manual/en/language.oop5.autoload.php

    Example from the mentioned documentation:

    <?php
    spl_autoload_register(function ($class_name) {
        include $class_name . '.php';
    });
    
    $obj  = new MyClass1();
    $obj2 = new MyClass2(); 
    ?>
    

    In this case spl_autoload_register is used to register the autoloader. The autoloader is a function which takes the class name, and includes the necessary class. For example you can use the autoloader function as used above, in which case the class name needs to be identical to the filename. This is a quite simple example, but a more advanced autoloader could check if files exist, check multiple locations, etc...

    Examples are mentioned in the comments on your original question.

    note: You will find other sources mentioning the __autoload($class) function. This function does exactly the same, but will be removed from PHP in future updates. Therefore, you are better off using spl_autoload_register

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同