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>";
} );
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()
:An alternative method would be to use
create_function()
. This way, you don't even have to change the definition of yourtemplate_func()
.