note 14190 added to function.array-walk.php
| From: | (Thomas Wolf) | Date: | Fri, 20 Jul 2001 20:56:25 +0000 |
| Subject: | note 14190 added to function.array-walk.php | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-15625@lists.php.net to get a copy of this message | ||
I just used array_walk for the first time and saw that there's a problem using class member
functions as callback for it. So first I tried to use array_walk($array,'MyCallback'); -
didn't work since 'MyCallback' is not a class member and I wanna call one. After this
I tried array_walk($array,'this->MyCallback'); and
array_walk($array,'$this->MyCallback'); without success. Next I tried it via pointers
and it worked perfectly.
So for you guys out there still having problems with it, you could alternatively use the third
array_walk parameter. Just pass a pointer to your class ($this) to it. An example:
// this is our 1st walk callback
function MyWalk1(&$item,$key,$ptr)
{
// access $ptr as it would be $this
// or the owner class
echo "key is '$key'\n";
echo "class member is '".$ptr->mystr."'\";
// walk into 2nd dimension ...
array_walk($item,'MyWalk2',$ptr);
}
// this is our 2nd walk callback
function MyWalk2(&$item,$key,$ptr)
{
// $ptr is a pointer to our class again
echo "key is '$key'\n";
echo "class member is '".$ptr->mystr."'\";
// walk into 3rd dimension ...
array_walk(...
}
class MyClass
{
var $array = ...;
var $mystr = "this is my string";
function myfunc()
{
// specify pointer to this class as third parameter (custom)
array_walk($this->array,'MyWalk1',$this);
}
}
... and everything works just very very fine. Hope this helped you. If so, be so kind and drop me a
mail. Thanks, Tom.
http://www.php.net/manual/en/function.array-walk.php