Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - How to call static function without instantiate object

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?

Example: I have class App\Helpers\Utilities.php with public function 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();

like image 976
boomdrak Avatar asked Jul 15 '16 08:07

boomdrak


2 Answers

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.
 }
}
like image 99
Basit Munir Avatar answered Sep 21 '22 05:09

Basit Munir


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
like image 27
Parth kharecha Avatar answered Sep 23 '22 05:09

Parth kharecha