Laravel使使用作用域解析操作符(::)调用类方法成为可能,而无需静态声明方法。
在PHP中,仅当静态方法声明为静态方法时,才能调用它们,例如:
class User {
public static function getAge() { ... }
}可以作为User::getAge();调用
在一个普通的PHP类中如何做到这一点。我想这是可能的,它需要使用设计模式或其他东西来完成。有人能帮我吗?
所以我上面的意思是,在php中可以实例化一个类并静态地调用它的方法。因为该功能已从以前版本中删除
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发布于 2020-03-02 17:12:27
我猜测您的User类实际上扩展了Laravel Model类。
这个类实现了一些被称为魔术方法的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);
}https://stackoverflow.com/questions/60485254
复制相似问题