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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38391105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:09:38  来源:igfitidea点击:

Laravel - How to call static function without instantiate object

phplaraveloopmodel-view-controllerweb

提问by boomdrak

Is there any way in Laravel (5.2) to call static and/or non-static function in a custom object without having to instantiate the referring object in all classes it is used?

在 Laravel (5.2) 中有什么方法可以在自定义对象中调用静态和/或非静态函数,而不必在它使用的所有类中实例化引用对象?

Example: I have class App\Helpers\Utilities.phpwith public function doBeforeTask()

示例:我有App\Helpers\Utilities.php公共功能的课程doBeforeTask()

I'm using this method in allot of classes within my project and it would be pretty if i could just call Utilities::doBeforeTask()or Utilities->doBeforeTask()without creating a instance of my Utilities object $obj = new Utilities();

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

回答by Basit Munir

define your method as static method. and call it anywhere with following code:

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

Utilities::doBeforeTask();

Code structure of file App\Helpers\Utilities.php

App\Helpers\Utilities.php文件的代码结构

namespace App\Library;

class Utilities {

 //added new user
 public static function doBeforeTask() {
  // ... you business logic.
 }
}

回答by Parth kharecha

Define your method as a static method. and call it anywhere

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

let's take an example

让我们举个例子

 namespace App\Http\Utility;

    class ClassName{

        public static function methodName(){
         // ... you business logic.
        }
    }

where you want to use specify the namespace

你想使用的地方指定命名空间

like this:

像这样:

use App\Http\Utility\ClassName;

ClassName::methodName();

Don't forget to run

别忘了奔跑

composer dump-autoload

回答by Frank Provost

Define static function

定义静态函数

class Foo
{

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

now call Foo::staticFunction()

现在调用 Foo::staticFunction()

回答by digout

If it's a method that you cannot change to static (i.e. it's a vendor file) then you can do this in PHP >= 5.4

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

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