Herkool
Herkool

Reputation: 67

Why should I assign my function to a variable?

While reading the Anonymous functions entry at the php.net, and looking at the provided example, I came across this section which mentions the second use case of these functions:

Closures can also be used as the values of variables.

I wonder why one should assign a method to a variable? What I am trying to understand here is what would be the advantage of this approach:

$greet = function($name)
{
    echo "Hello $name";
};

$greet('World');
$greet('PHP');

over a piece like this:

function greet($name) 
{
    echo "Hello $name";
}
greet('World');
greet('PHP');

that justifies it? Is it just a alternative way to write a piece of code? Or, in some cases, in more advanced designs, it will build the room for more descriptive code base?

Upvotes: 3

Views: 1454

Answers (2)

Dharman
Dharman

Reputation: 33374

This is a good question. The thing with anonymous functions is that they should generally be anonymous. When you assign them to a variable you give them a name, which defeats the purpose.

In a simple examples they work the same as named functions:

function named($a) {
    echo 'This is '.$a;
}

$unnamed = function ($a) {
    echo 'This is '.$a;
};

function caller($callee, string $name) {
    $callee($name);
}

caller('named', 'named');
caller($unnamed, 'unnamed');

The only difference is that the type of $callee is once a string and the other time it is a function.

The difference:

Imagine you have a scenario when you would like to capture the current scope into a function and pass it into another function for execution as callback.

$v1 = 2;
$a = function() use($v1) { return $v1; };
// or 
$a = fn() => $v1;
$v1 = 4;

function named($callback) {
    $v1 = 3;
    echo $callback();
}

named($a); //output is 2

With normal functions you would have to pass the value as an argument to the function. At the time of calling the function the value has changed, which means that you would need to capture the value yourself when defining the function.

The fact that you can assign a closure to a variable doesn't mean you must do so. It means that the function can be passed around as a first-class citizen.

Consider this code for example, which catches a private property in B class and passes it inside of closure to A class:

class A {
    private $someVar = 'Hello world!';

    public function __construct($callback) {
        $callback();
    }
}

class B {
    private $someVar = 'Bogus!';

    public function createCallback() {
        return function () {
            echo $this->someVar;
        };
    }
}

$b = new B();
new A($b->createCallback()); // echo Bogus!

Upvotes: 5

Stephen R
Stephen R

Reputation: 3917

You can use “variable assigned” function within HEREDOC strings:

Silly (untested) example:

$mult = function( $n ) { return $n * 2; }
$x = 5;

$str = <<<TEXT
$x times two equals {$mult($x)}.
TEXT;

Upvotes: 0

Related Questions