【问题标题】:How does Laravel dynamically call a class method statically without implicitly using the static keyword for the method in PHP?Laravel 如何在 PHP 中不隐式使用 static 关键字来静态地动态调用类方法?
【发布时间】:2020-06-14 12:53:23
【问题描述】:

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

【问题讨论】:

  • 你能否提供一个 Laravel 中这种方法的示例以及如何调用它以明确你所指的内容?
  • 一个例子是如何使用 Blade 类来调用它的方法 example Blade::compileString($param)
  • 前两个视频here 您也会感兴趣。
  • 感谢 Delena 的视频真的很有帮助。

标签: php static-methods facade


【解决方案1】:

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

【讨论】:

  • 不,我没有使用 Laravel 模型。我想知道如何在原始 PHP 中完成它。你能帮忙举一个现实世界的例子吗
  • @A.L. 这个答案非常有帮助,但我正在寻找的东西在这里得到了解释:sitepoint.com/… 非常感谢
猜你喜欢
  • 1970-01-01
  • 2012-02-08
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 2011-01-07
  • 2023-02-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多