* Francisco M. Marzoa Alonso <[EMAIL PROTECTED]>:
> I want to wrote a function that receives another function as parameter 
> that will be used as a Callback. Well, better a bit of code than 
> thousand words:
>
> class TreeNode {
> ...
>     function Traverse ( CallBack ) {
>         $rtn = CallBack ($this);
>         foreach ($this->Sons as $Son) {
>             $Son->Traverse ( CallBack );
>         }
>         return $rtn;
>     }
> ...
> }
>
> And later I'll do something as:
>
> function CallBack ( $Node ) {
>     echo $Node->Name;
> }
>
> $MyTreeNode->Traverse ( CallBack );
>
> ...
>
> Hope you understand what I'm trying to do. Can it be done as is or am I 
> on the wrong way?

Two ways to do it:

1) Pass a string that is the callback function's name; then call it a
   dynamic variable function:

   function Traverse($callback)
   {
       $rtn = $callback($this);
       ...
   }

2) Use a PHP callback pseudotype (http://php.net/pseudo-types):

   function Traverse($callback)
   {
       // Calls the callback with $this as its argument:
       $rtn = call_use_func($callback, $this); 
       ...
   }

Callbacks can be either a string containing a function name or an array
with the first element either a class name or object reference and the
second argument a method name (the first does a static method call, the
second an object method call).

-- 
Matthew Weier O'Phinney           | mailto:[EMAIL PROTECTED]
Webmaster and IT Specialist       | http://www.garden.org
National Gardening Association    | http://www.kidsgardening.com
802-863-5251 x156                 | http://nationalgardenmonth.org

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to