I’m used to C++ where anything can be passed to anyone. I’m wondering about the possibility of passing functions as arguments in PHP. Google has been pretty useless since any combination of those keywords gets you thousands of articles on standard function arguments.
The code below works, more-or-less, as the C++ version would but the code is all in one file.
<?php
function foo($wd="No arg sent<br>") {
echo $wd;
}
function test($fn) {
$fn("Inside Test<br>");
}
$bar = 'foo';
$bar();
$bar("Argument sent<br>");
test($bar);
?>
Output:
No arg sent
Argument sent
Inside Test
Here’s an example of what I’m thinking of: Say you wanted to instantiate a PHP class and set it’s sort function and compare function to use the code defined in the current file (or an included file). Something like this:
include "tableClass.inc.php"
$table = new table(10,20);
mySortFunction($data, $compareFn) {
.. etc.
}
myCompareFunction($s1, $s2) {
return $s1 > $s2;
}
$sFn = 'MySortFunction';
$cFn = 'myCompareFunction';
$table->setSortFunction($sFn);
$table->setCompareFunction($cFn);
$table->sort();
Where the code in the class would look like this:
function sort() {
return ($this->sortFunction($this->data,$this->compareFunction));
}
I can think of several uses for something like this. Does anyone know offhand whether it will work reliably in PHP or not?