This is an example PHP program that demonstrates how to use callback functions and anonymous function with the use command.
<?php // A callback function that takes 2 parameters function Display($iValue, $iKey) { echo "{$iKey} => {$iValue}<br />"; } // A callback function that takes 3 parameters function Multiply($iValue, $iKey, $iMultiplier) { echo "{$iKey} => {$iValue}: {$iValue} * {$iMultiplier} = ".($iValue*$iMultiplier)."<br />"; } // Create the array to which the callbacks will applied. $iaArray = []; for ($i = 0; $i < 5; ++$i) { $iaArray[] = 10 * $i; } // Using a callback function that takes 2 parameters echo "<b>key => value</b><br />"; array_walk($iaArray, 'Display'); echo "<hr />"; // Using a callback function that takes an additional parameters echo "<b>key => value: product</b><br />"; array_walk($iaArray, 'Multiply', 2); echo "<hr />"; // An anonymous function with the use specifier to pass additional values. $iMultiplier = 17; $iSummand = 1; echo "<b>key => value: product + summand</b><br />"; array_walk($iaArray, function($iValue, $iKey) use ($iMultiplier, $iSummand) { echo "{$iKey} => {$iValue}: {$iValue} * {$iMultiplier} + {$iSummand} = ". (($iValue*$iMultiplier) + $iSummand)."<br />"; }); ?>
© 20072025 XoaX.net LLC. All rights reserved.