Home Account

anonymous and inline functions with php

2012-11-20 18:25 dennis iversen

Tags: php

The following is not quite the same as inline function in e.g. c or c++ even though they resemble them in one way or another.

Playing around with PHP I found that inline functions are possible. Consider the following:

<?php

function test () {
    function test2() {
        echo "hello world";
    }
    test2();
}

test(); // this will echo "hello world"

You could also add the above inline function in a class method.

You can only define these functions in the same scope. The following will fail with : PHP Fatal error: Call to undefined function test3()

<?php

function test () {
    function test2() {
        function test3() {
            echo "hello";
        }
    }
    test3();
}

test3(); // this will fail

While this example with deeper nesting is ok (because I call them at the same scope level):

<?php

function test () {
    function test2() {
        function test3() {
        echo "hello";
    }
        test3();
    }
    test2();
}

test(); // this will echo "hello world"
// but test2 will fail

You can only define an inline function once: The following will fail with: Fatal error: Cannot redeclare test2()

<?php

function test () 
    function test2() {
        echo "hello world";
    }
    test2();
}

function _test () {
    function test2() {
        echo "hello world";
    }
    test2();
}

test();
_test(); 

The solution to the above problem will be to just use an anonymous function (which is a function without a name), like in this example:

<?php

function test () {
    $test = function () {
    echo "hello world";
    };
    $test();
}

function _test () {
    $test = function () {
    echo "hello world";
    };
    $test();
}   

test();
_test(); // this will echo "hello world"

Note that you need to end an anonymous function with ;. This will not work

<?php

$test = function () {
    echo "hello world";
}

While this will work:

<?php

$test = function() {
    echo "hello world";
};

Anonymous functions can be nice to use e.g. if you want to make a callback or filter something with your function:

<?php

function test($num, $func) {
    while ($num) {
        $func($num);
        $num--;
    }
}

$anon = function () {
    echo "hello world\n";
};

test(3, $anon); // this will print "hello world" 3 times

Therefor you should always prefer anonymous functions over inline functions. as anonymous functions don't clutter up the main name space.

This page has been requested 18964 times