Laravel - How to call static function without instantiate object

36,298

Solution 1

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.
 }
}

Solution 2

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

Solution 3

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

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

Solution 4

Laravel also has a Facade implementation, which is probably what TS had in mind. These Facades will do basically everything for you and most likely also solves the "vendor-file" issue.

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

basically you have to provide an instance of it and point your facade to it, which in turn get's an alias you register. everything is explained in above url.

Solution 5

Define static function

class Foo
{

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

now call Foo::staticFunction()

Share:
36,298
boomdrak
Author by

boomdrak

Working as full stack developer with infrastructure responsibilities.

Updated on August 21, 2020

Comments

  • boomdrak
    boomdrak over 3 years

    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();

  • boomdrak
    boomdrak almost 8 years
    But does it not require some sort of autoload or implementation in composer.json such as service provider or alias?
  • Frnak
    Frnak almost 8 years
    If you want to use it everywhere you can either require it in the autoload or add it as dep in composer
  • NoBugs
    NoBugs over 4 years
    Not sure if you're supposed to create it but there is no app/helpers folder in Laravel 6.
  • SomeOne_1
    SomeOne_1 over 3 years
    @boomdrak, no not in this case, because it's simple plain PHP implementation. All that is required for autoloading is ofcourse the psr-4 compliant namespace. What you are thinking of is Laravel's Facade.