首页 > 解决方案 > 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

标签: phpstatic-methodsfacade

解决方案


我的猜测是您的 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);
}

推荐阅读