Re: reference a function in a class from array_walk()

From: Date: Sat, 21 Jun 2003 20:55:20 +0000
Subject: Re: reference a function in a class from array_walk()
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-152407@lists.php.net to get a copy of this message
On Sat, 21 Jun 2003 19:24:26 +0200, you wrote: >I want to call this generic echo function within a class, but have >trouble referencing the output function with $this-> . >Any suggestions? Maybe there is a better solution to this? > >This is within a class: > >[snip] ># generic WALK functions > function walkit($array) > { > array_walk($array,"$this->output"); //not >working > } > > function output($item,$key) > { > echo "$key. $item<br />\n"; > } You want to apply a function that's wrapped in a class to a given array? My first reaction is that your best approach is to invoke a function within a class, without creating an instance of that class. See the :: operator. The following code covers several ways of calling functions wrapped in classes. You probably want the last two calls: <? /* Class A has method B */ class A { function B ($s = "None") { echo ("<p>input : $s</p>"); } } /* $C is an instance of A */ $C = new A (); /* $D is an array of strings */ $D = array('item 1', 'item 2', 'item 3', 'item 4'); /* invoke A::B */ A::B ('call 1'); /* invoke $C->B */ $C->B ('call 2'); /* invoke A::B via call_user_func() */ call_user_func (array('A', 'B'), 'call 3'); /* invoke $C->B via call_user_func() */ call_user_func (array($C, 'B'), 'call 4'); /* invoke A::B via call_user_func_array() */ call_user_func_array (array('A', 'B'), array('call 5')); /* invoke $C->B via call_user_func_array() */ call_user_func_array (array($C, 'B'), array('call 6')); /* apply A::B to $D via array_walk() */ array_walk ($D, array('A', 'B')); /* apply $C->B to $D via array_walk() */ array_walk ($D, array($C, 'B')); ?>

« previous php.general (#152407) next »