猿问

为类使用 PHP 命名空间但收到使用错误

我收到错误:Fatal error: Uncaught Error: Class 'Services\EncryptionService' not found

  • 班级在 <root>\services\EncryptionService.php

  • 班级在第一排 namespace Services;

  • PHP文件调用类 <root>\db\db_change_password.php

  • PHP 文件调用类在第一行 use Services\EncryptionService;

用法:

$encryption_service = new EncryptionService;
$encryptedPassword = $encryption_service->encrypt($password);

并提供致命错误。

编辑:

  • autoload_classmap.php

  • autoload_files.php

  • autoload_namespaces.php

  • autoload_psr4.php

  • autoload_real.php autoload_static.php


翻翻过去那场雪
浏览 167回答 1
1回答

饮歌长啸

我认为你应该使用自动加载类来加载你使用的任何类,如果你不使用命名空间创建文件夹,将此代码放在你创建的文件夹上的文件中,然后将它包含或要求在索引和 APP_PATH const 中作为路径项目我希望这对你有帮助<?php&nbsp; namespace Services\lib;&nbsp; class Autoload&nbsp; {&nbsp; &nbsp; public static function autoload($className){&nbsp; &nbsp; //remove the main namespace&nbsp; &nbsp; $className=str_replace("Services","",$className);&nbsp; &nbsp; $className=str_replace("\\","/",$className);&nbsp; &nbsp; $className=$className.".php";&nbsp; &nbsp; $className=strtolower($className);&nbsp; &nbsp; //echo $className;&nbsp; &nbsp; if(file_exists(APP_PATH.$className)){&nbsp; &nbsp; &nbsp; &nbsp; require_once (APP_PATH.$className);&nbsp; &nbsp; }&nbsp; }&nbsp; }spl_autoload_register(__NAMESPACE__.'\Autoload::autoload');
随时随地看视频慕课网APP
我要回答