phpphp-closures

PHP closure return multiple functions


I'm trying to achieve almost similar things/properties of closure in PHP which is available in JS.

For example

function createGreeter($who) {
    return function(){
        function hello() use ($who) {
            echo "Hi $who";
        }

        function bye() use($who){
            echo "Bye $who";
        }
    };
} 

I know my syntax is incorrect, this what I'm trying to achieve.

What I've done so far is.

function createGreeter() {
    $hi = "hi how are you.";
    $bye = "bye wish you luck.";
    return function($operation) use ($hi, $bye){
        if ($operation == "a") return $hi;
        elseif ($operation == "b") return $bye;
    };
}
$op = createGreeter();
echo $op("a"); #prints hi how are you.
echo $op("b"); #prints bye wish you luck.

Please look does PHP allows us to do this.


Solution

  • You could return an anonymous class which is created with the $who and then has methods which output the relevant message...

    function createGreeter($who) {
        return new class($who){
            private $who;
            public function __construct( $who ) {
                $this->who = $who;
            }
            function hello() {
                echo "Hi {$this->who}";
            }
    
            function bye(){
                echo "Bye {$this->who}";
            }
        };
    } 
    $op = createGreeter("me");
    echo $op->hello();    // Hi me
    echo $op->bye();      // Bye me