Assigning function to class property in the class' constructor?

Viewed 44

I came across this code in the Laravel codebase, where a function is assigned to a property ($this->userResolver) within the constructor. What is the purpose of this?

The userResolver is not using any arguments passed to the constructor. The class in question is the AuthManager class (Illuminate/Auth/AuthManager.php).

If I remove the $this->userResolver code here in the constructor, everything still seems to work just fine. Would love if somebody can explain this one, thanks!

   public function __construct($app)
    {
        $this->app = $app;
        $this->userResolver = function ($guard = null) {
            return $this->guard($guard)->user();
        };
    }
1 Answers

Notice that is is setting userResolver to point to a function. That function has a parameter ($guard). In general, this is a technique to add a function to an object.

Related