php - Laravel 如何在不隐式使用 PHP 中方法的 static 关键字的情况下,动态地静态调用类方法?
问题描述
Laravel 可以使用范围解析运算符 (::) 调用类方法,而无需静态声明该方法。
在 PHP 中,您只能在声明为静态方法时调用它们,例如:
class User {
public static function getAge() { ... }
}
可以称为User::getAge();
如何在普通的 PHP 类中做到这一点。我想它可能需要使用设计模式或其他东西来完成。谁能帮我吗?
所以我上面的意思是可以实例化一个类并在 php.ini 中静态调用它的方法。由于该功能已从以前的版本中删除
class Student {
public function examScore($mark_one, $mark_two) {
//some code here
}
}
如何以这种方式访问它
$student = new Student;
$student::examScore(20, 40);
我谈到了 Laravel,因为它允许你给你的类起别名并以这种方式调用它Student::examScore(20,40);
一种叫做外观模式的东西。举例说明会有所帮助。
经过长时间的搜索,我在这里找到了一篇解释它的文章:
https://www.sitepoint.com/how-laravel-facades-work-and-how-to-use-them-elsewhere
解决方案
我的猜测是您的 User 类实际上扩展了 LaravelModel
类。
此类实现了一些 PHP 所谓的魔术方法。你可以在这里找到我们关于它们的信息: https ://www.php.net/manual/en/language.oop5.magic.php
其中之一是__callStatic
。
在Model.php
:
/**
* Handle dynamic static method calls into the method.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public static function __callStatic($method, $parameters)
{
return (new static)->$method(...$parameters);
}
推荐阅读
- r - 如何在 R 中将带有 unicode 字符的表格保存为 pdf
- swift - Fluent:如何按相关性对过滤的实体进行排序?
- flutter - 选择行后打开折叠的 ListTile
- javascript - 如何获取单击的按钮的 ID,然后将其用作其他内容的外键?(ASP.NET MVC)
- java - 如何在 ZK 7.X 中订阅 KeyEvent
- ios - 如何在 Ionic/Cordova 构建中正确引用 iOS 3rd 方框架,使其不会抛出 dyld:未加载库:@rpath 错误
- git - 合并从本地分支发送到主分支的请求,同时将一些更改推送到本地分支
- bash - 从 MATLAB 调用 Anaconda 环境:未找到 Conda 命令
- c# - SQL - 使用分组方式选择,从具有最大值(日期)的寄存器中获取数据
- android - 我的回收站视图未显示任何 Firebase 图像