Search code examples
phplaraveloopmodel-view-controller

Laravel - How to call static function without instantiate object


Is there any way in Laravel (5.2) to call static and non-static functions in a custom object without instantiating the referring object in all classes used?

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

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


Solution

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

    Utilities::doBeforeTask();
    

    Code structure of file App\Helpers\Utilities.php

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