optimization - optimal way of passing multiple callback functions as arguments? -
i have function used in cli or web application, being said, there little difference in process; example: if i'm using function cli it'll use text progress bar, doesn't make sense if i'm using function web application.
the function loop; i'm looking way make function flexible making possible pass code argument it'll executed @ end of each loop cycle. if i'm using function in cli; i'll pass progress incremental function advance progress bar, , on.
my current solution pass progress bar object instance, think isn't proper solution; because doesn't seem flexible long run.
a demonstration example of i'm doing:
function myfunction($progressbar = null) { for($i = 0; $i......) { //do stuff .... //finally... if(!empty($progressbar)) $progressbar->advance(); } } so, if want add function @ end of loop, i'll have pass argument , call manually later; said, doesn't seem right.
i'm thinking of using callback function(an anonymous function being passed myfunction) proper way of doing that; should make each callback function individual argument? or, make more flexible, should grouping callback functions in array(if that's possible).
yes, can use callbacks this.
function myfunction($progressbar = null, callable $callback = null) { for($i = 0; $i......) { //do stuff .... //finally... if(!empty($progressbar)) $progressbar->advance(); } if ($callback){ //execute callback if passed parameter $callback(); } } also, can specify parameters anonymous function:
example: want echo @ point.
myfunction($progressbar) ; //no need yet myfunction($progressbar, function($result){ echo $result ; }) ; //now want execute so, handle in appropriate way:
if ($callback){ //execute callback if passed parameter $callback("all fine"); //execute callback , pass parameter } array of callbacks may useful in case like:
$callbacks = array( "onstart" => function(){ echo "started" ; }, "onend" => function(){ echo "ended" ; } ) ; function myfunc($progressbar = null, $callbacks){ if (isset($callbacks["onstart"]) && is_callable($callbacks["onstart"])){ $callbacks["onstart"]() ;//execute on start. } //execute code if (isset($callbacks["onend"]) && is_callable($callbacks["onend"])){ $callbacks["onend"]() ;//execute on end. } }
Comments
Post a Comment