samedi 2 juillet 2016

Nested Functions, First Class Functions in PHP

With functions in Python, Js and PHP they all say they are first class objects. I want to make sure I got the PHP example right. Is there any other way of porting this code to PHP?

Python 3:

def a():
    print("init")
    def b():
        print("inside")
        def c():
            print("inception")
    return c
return b


a()()() 

Result

init
inside
inception
[Finished in 0.1s]

Javascript (node):

function a() {
    console.log("init")
    function b()
    {
        console.log("inside")
        function c()
        {
            console.log("inception")
        }
        return c
    }
    return b
}

s = a()()()

Result

init
inside
inception
[Finished in 0.2s]

PHP 5.5:

function a()
{
    echo "init".PHP_EOL;
    $x = function()
    {
        echo "inside".PHP_EOL;
        $y = function()
        {
            echo "inception".PHP_EOL;
        };
        echo "b".PHP_EOL;
        return $y;
    };
    return $x;
}

a()()();

Result

Parse error: syntax error, unexpected '('

lets try again in PHP

$b = a();
$c = $b();
$c();

Result

init
inside
inception
[Finished in 0.1s]

Is that the only way to call nested function in PHP?

UPDATE Follow up question, in PHP can you return a function the same way as in Python or JS ? or must it be assigned to a variable as a closure first.

Aucun commentaire:

Enregistrer un commentaire