Laravel-如何在没有实例化对象的情况下调用静态函数


Laravel - How to call static function without instantiate object

Laravel(5.2)中是否有任何方法可以在自定义对象中调用静态和/或非静态函数,而无需在使用它的所有类中实例化引用对象?

示例:我有具有公共函数App'Helpers'Utilities.php的类doBeforeTask()

我在项目中的大量类中使用此方法,如果我可以在不创建 Utilities 对象的实例的情况下调用 Utilities::doBeforeTask()Utilities->doBeforeTask(),那就太好了$obj = new Utilities();

方法定义为静态方法。 并使用以下代码在任何地方调用它:

Utilities::doBeforeTask();

文件应用程序''帮助程序''实用工具的代码结构.php

namespace App'Library;
class Utilities {
 //added new user
 public static function doBeforeTask() {
  // ... you business logic.
 }
}

将方法定义为静态方法。 并在任何地方调用它

让我们举个例子

 namespace App'Http'Utility;
    class ClassName{
        public static function methodName(){
         // ... you business logic.
        }
    }

要使用的位置指定命名空间

喜欢这个:

use App'Http'Utility'ClassName;
ClassName::methodName();

别忘了跑步

composer dump-autoload

如果它是一个你不能更改为静态的方法(即它是一个供应商文件),那么你可以在 PHP 中执行此操作>= 5.4

$something = (new Something)->foo("bar"); 

定义静态函数

class Foo
{
    public static function staticFunction() {
        return 'Hello World';
    }
}

现在调用 Foo::staticFunction()

> Laravel也有一个Facade实现,这可能是TS的想法。这些外观基本上可以为您做所有事情,并且很可能还可以解决"供应商文件"问题。

https://www.larashout.com/creating-custom-facades-in-laravel

基本上,您必须提供它的一个实例并将您的外观指向它,这反过来又会获得您注册的别名。 一切都在上面的 URL 中解释。

对于动态静态调用

Utilities::anyMethod($args);

PHP代码

<?php
namespace App'Library;
class Utilities {
  public function anyMethod() {
     // simple code
  }
  public static function __callStatic($method, $args)
  {
      $instance = static::resolveFacadeInstance(static::getFacadeAccessor());
      switch (count($args))
      {
        case 0:
            return $instance->$method();
        case 1:
            return $instance->$method($args[0]);
        case 2:
            return $instance->$method($args[0], $args[1]);
        case 3:
            return $instance->$method($args[0], $args[1], $args[2]);
        case 4:
            return $instance->$method($args[0], $args[1], $args[2], $args[3]);
        default:
            return call_user_func_array(array($instance, $method), $args);
      }
    }
  }
}
相关文章: