Search code examples
phpanonymous-functionanonymous-methods

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


Solution

  • 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;
    };