Re: Callback function as parameter
| From: | Matthew Weier O'Phinney | Date: | Wed, 10 Nov 2004 19:57:55 +0000 |
| Subject: | Re: Callback function as parameter | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-201713@lists.php.net to get a copy of this message | ||
* Francisco M. Marzoa Alonso <fmmarzoa@gmx.net>:
> 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:matthew@garden.org
Webmaster and IT Specialist | http://www.garden.org
National Gardening Association | http://www.kidsgardening.com
802-863-5251 x156 | http://nationalgardenmonth.org