php - 从外部类调用具有依赖项 PHP 的方法
问题描述
问题:
我有一个index.php
包含多个作曲家依赖项的文件。在index.php
文件内部,我试图在不同的 php(比方说auth.php
)文件中从外部类调用静态方法,如下所示:
/*creating a class instance*/
$var = new AuthClass();
/*accessing an outside class method*/
$var = AuthClass::checkTime($tokenCode);
问题是checkTime
类中的方法也需要一个 composer 依赖项,虽然该文件与 index.php 位于同一文件夹中并且 index.php 包含在内,但该文件不被继承。
PHP Fatal error: Uncaught Error: Class 'Token' not found
我已经尝试了一切 - 从添加 require_once/include 'index.php' 到将作曲家自动加载复制到 AuthClass 代码内外的 auth.php ,但没有任何效果,我仍然遇到同样的错误。
附加代码:
索引.php
require __DIR__ . '/src/vendor/autoload.php';
$argument1 = $_GET['argument1'];
$tokenCode = $_GET['tokenCode'];
include 'config/database.php';
include 'objects/program1.php';
include 'auth.php';
use ReallySimpleJWT\Token;
use Carbon\Carbon;
$secret = "somesecret";
if (($_SERVER['REQUEST_METHOD']) == "GET") {
if ($_GET['url'] == "bankquery") {
if($tokenCode===NULL){
echo "no correct token provided";
print($results);
} else {
$results = Token::validate($tokenCode, $secret);
if ($results = 1){
$var = new AuthClass();
$var = AuthClass::checkTime($tokenCode);
} else {
echo "no correct token provided";
}
}
} else {
echo "some GET other query";
}
?>
授权文件
// loading composer
require __DIR__ . '/src/vendor/autoload.php';
//loading my index.php file
include 'index.php';
//using composer dependencies
use ReallySimpleJWT\Token;
use Carbon\Carbon;
class AuthClass{
public static function checkTime($tokenCode){
// getting payload from token code by accessing the composer dependency method in a class Token
$received = Token::getPayload($tokenCode);
return $received;
}
}
?>
需要帮助,伙计们。
解决方案
您在AuthClass
定义之前使用 - 尝试include 'index.php';
在文件末尾移动行。
您还应该vendor/autoload.php
只包含一次 - 您不需要在每个文件中重复此操作,只需确保它包含在处理请求的条目文件的顶部即可。
但这更像是设计问题的结果。您应该AuthClass
在单独的文件中定义并避免其中的任何其他副作用 - 文件应该只定义类。这是PSR-1 规则的一部分:
文件应该声明符号(类、函数、常量等)或引起副作用(例如生成输出、更改 .ini 设置等),但不应该两者都做。
由于您已经在使用 Composer 的自动加载器,因此注册自己的自动加载规则应该相对容易,因此 Composer 的自动加载器将负责类的自动加载。
如果此时您仍然得到Class 'X' not found
,您可能没有安装某些依赖项或您的自动加载规则不正确。
推荐阅读
- excel - 在 VBA excel 上复制和粘贴
- algorithm - GLSL 快速屏幕模式
- angular - Angular Material Mat Menu 禁用 matMenuTriggerFor
- powershell - 使用 powershell 从另一台服务器查找服务器正常运行时间
- javascript - JavaScript 中的闭包和原型设计有什么区别?
- php - Laravel 合并 Laravel 包中的配置
- java - 使用 Java 8 在 Spark 2 中进行方差分析统计计算
- c# - 另一台电脑上的 C# 数据库文件应用程序
- r - 快速将列表中的所有矩阵组合相乘
- android-studio - 如何按顺序重新排列 Kotlin 代码?