How to implement a function template in PHP 5.2 like this in PHP 5.3?

323 Views Asked by At

This code runs very well in PHP 5.3 but not in PHP 5.2. How can you implement something like this in PHP 5.2?

echo "Calling func....<br/>";
function template_func( $data=array(), $func ) {
    echo "<ul>";
    foreach ($data as $k => $v) {
        $func( $v );    
    }
    echo "</ul>";
}

$data = array( 1, 2, 3, 4, 5 );

template_func( $data, function ( $v ) { 
    echo "<li>$v</li>"; 
} );

template_func( $data, function ( $v ) { 
    echo "<li><span class='style'>$v</span></li>"; 
} );
2

There are 2 best solutions below

3
On

You can use call_user_func() / call_user_func_array(). You will have to pass the function name as a string. You can also call methods and static methods this way, please check the manual.

You could also use is_callable() to verify whether the parameter can be called as a function.

A simple example with call_user_func():

function template_func( $data=array(), $func ) {
    echo "<ul>";
    foreach ($data as $k => $v) {
        call_user_func($func, $v);    
    }
    echo "</ul>";
}

function spannedList ( $v ) { 
    echo "<li><span class='style'>$v</span></li>"; 
}
template_func($data, 'spannedList');

An alternative method would be to use create_function(). This way, you don't even have to change the definition of your template_func().

0
On

Simply change the anonymous functions to create_function:

template_func( $data, create_function( '$v', '
    echo "<li>$v</li>"; 
' ) );

template_func( $data, create_function( '$v', '
    echo "<li><span class=\'style\'>$v</span></li>"; 
' ) );