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条)

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能