note 113007 added to language.types.callable
| From: | urkerlan at gmail dot com | Date: | Sat, 17 Aug 2013 13:17:30 +0000 |
| Subject: | note 113007 added to language.types.callable | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-195994@lists.php.net to get a copy of this message | ||
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>";
?>
----
Server IP: 69.147.83.199
Probable Submitter: 217.121.76.24
----
Manual Page -- http://php.net/manual/en/language.types.callable.php
Edit -- https://master.php.net/note/edit/113007
Del: integrated -- https://master.php.net/note/delete/113007/integrated
Del: useless -- https://master.php.net/note/delete/113007/useless
Del: bad code -- https://master.php.net/note/delete/113007/bad+code
Del: spam -- https://master.php.net/note/delete/113007/spam
Del: non-english -- https://master.php.net/note/delete/113007/non-english
Del: in docs -- https://master.php.net/note/delete/113007/in+docs
Del: other reasons-- https://master.php.net/note/delete/113007
Reject -- https://master.php.net/note/reject/113007
Search -- https://master.php.net/manage/user-notes.php