Albertestein
Albertestein

Reputation: 19

One anonymous method call in another method in php

I have a problem in calling an anonymous method in another anonymous method.

<?php
    $x = function($a)
    {
        return $a;
    };
    $y = function()
    {
        $b = $x("hello world a");
        echo $b;
    };
    $y(); 
?>

Error:

Notice: Undefined variable: x in C:\xampp\htdocs\tsta.php on line 7

Fatal error: Function name must be a string in C:\xampp\htdocs\tsta.php on line 7

Upvotes: 2

Views: 80

Answers (3)

m1lt0n
m1lt0n

Reputation: 361

Both @argobast and @hiren-raiyani answers are valid. The most generic one is the first, but the latter is more appropriate if the only consumer of the first anonymous function is the second one (ie $x is used only by $y).

Another option is (this one needs a change in the signature of the $y function) is to pass the anon. function as an argument to the function:

<?php

$x = function($a) 
{
    return $a;
};

$y = function(Closure $x)
{
    $b = $x('hello world a');
    echo $b;
};

$y($x);

This kind of "dependency injection" seems a bit cleaner to me instead of having a hidden dependency on $x with a 'use', but the choice is up to you.

Upvotes: 0

arbogastes
arbogastes

Reputation: 1328

Add use to your $y function, then scope of $y function will see $x variable:

$y = function() use ($x){
    $b = $x("hello world a");
    echo $b;
};

Upvotes: 4

Hiren Raiyani
Hiren Raiyani

Reputation: 744

You have to use anonymous function in same block.

<?php

$y = function(){
    $x = function($a){
        return  $a;
    };
    $b = $x("hello world a");
    echo $b;
};
$y();

Good Luck!!

Upvotes: -1

Related Questions