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 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题