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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度