首页 > 解决方案 > 命名空间 autoloading_register 未捕获错误:找不到类

问题描述

我正在尝试在我的 php 文件中使用命名空间。一切正常,直到我把它放到网上。比我有这个错误:

致命错误:未捕获的错误:在 /home/serafvc355/domains/imdbuddy.be/public_html/login.php:18 中找不到类 'classes\Buddy\User' 堆栈跟踪:在 /home/serafvc355/ 中抛出 #0 {main} domain/imdbuddy.be/public_html/login.php 第 18 行

登录.php

<?php

  include_once(__DIR__ . "/bootstrap.include.php");

  include_once 'autoload.php';


   if (!empty($_POST)) {

    //Put fields in variables
    $email = $_POST['email'];
    $password = $_POST['password'];

    if (!empty($email) && !empty($password)) {
    //If both fields are filled in, check if the login is correct

      if (classes\Buddy\User::checkPassword($email, $password)) {
      $user = new classes\Buddy\User($email);

        if ($_POST['captcha'] == $_SESSION['digit']) {
          if ($user->getActive() == 1) {
          $_SESSION['user'] = $email;
          header("Location: index.php");
         } else {
          $error = "Please confirm your account";
         }
      } else {
       $error = "Wrong Captcha";
      }
   } else {
     $error = "Sorry, we couldn't log you in.";
   }
 } else {

  //If one of the fields is empty, generate an error
  $error = "Email and password are required.";
  }
  }

 ?>

自动加载.php

<?php
    spl_autoload_register(function($className) {
    $file = dirname(__DIR__) . '\\' . $className . '.php';
    $file = str_replace('\\', DIRECTORY_SEPARATOR, $file);
    echo $file;
    if (file_exists($file)) {
    include $file;
}
});

用户.php

<?php

  namespace classes\Buddy;

  class User
  {
   private $id
   ...

文件结构

classes > Buddy > User.php 

标签: phpclassnamespaces

解决方案


可能它可以通过以下方式修复:

require 'autoload.php';
use classes\Buddy\User;
//in login.php

然后像这样使用

if (User::checkPassword($email, $password))

但也许类没有正确加载或命名空间错误不确定..


推荐阅读