Entry
How do I pass a user defined function to a class and call it from there?
Aug 25th, 2003 19:16
Perry Keller, dingy,
Passing a function to a function is commonly needed for traversing a
list or a tree. In this example, I have a class Tree that has a member
function breadthFirstTravese as follows:
class Tree{
var $name // string
var $children // array of Tree
.
.
.
function breadthFirstTraverse($visit){
$visit($this);
if ($this->children != NULL)
foreach ($this->children as $value)
$value->breadthFirstTraverse($visit);
}
.
.
.
}
somewhere else you define the specific function to perform on each node
for example to print a directory like structure:
function Visit($node){
$tabstr = "";
for ($i=0; $i < $node->level; $i++) $tabstr .= " ";
echo "$tabstr $node->name<br />";
}
function Visit2($node){
// some other process
}
then you can pass the function like this:
$t = new Tree($foo) // whatever variables you need
$func = "Visit";
$t->breadthFirstTraverse($func);
$func = "Visit2";
$t->breadthFirstTraverse($func);