note 113006 deleted from language.types.callable by peehaa
| From: | peehaa@php.net | Date: | Mon, 19 Aug 2013 17:20:03 +0000 |
| Subject: | note 113006 deleted from language.types.callable by peehaa | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-196016@lists.php.net to get a copy of this message | ||
Note Submitter: urkerlan at gmail dot com
----
For people looking for simple callback inside of a function call php supports the observer pattern.
<?php
//this code will echo test 10 times
function test($function){
$test = 'hallo';
for($a = 0; $a < 10; $a++){
$function($test, $a);
}
}
test(function($test, $a){
echo "$test - $a <br>";
});
?>
I like this, its very handy for more advanced code. The only problem is that variables declared
inside the callback function can not be reached so easily form the outside as in javascript.
<?php
$options = array(
0 => array('name', 'value'),
1 => array('name', 'value'),
2 => array('name', 'value'),
3 => array('name', 'value'),
4 => array('name', 'value')
);
function loop_options($options, $name, $function){
$focus = false;
if(isset($_REQUEST[$name])){
$focus = true;
}
foreach($options as $key => $option){
$function($key, $option[0], $option[1], $focus);
}
}
$html = '';
loop_options($options, 'form', function($key, $name, $value, $focus){
$selected = '';
if($focus){
$selected = 'selected';
}
//this will fail you need to set global
global $html;
$html .= "<option value='$value' $selected>$name</option>";
});
echo "<select name='form'>$html</select>";
?>