tags:

views:

50

answers:

1

If I use array_walk inside a class function to call another function of the same class

class user
{
   public function getUserFields($userIdsArray,$fieldsArray)
   {

     if((isNonEmptyArray($userIdsArray)) && (isNonEmptyArray($fieldsArray)))
     {
         array_walk($fieldsArray, 'test_print');
     }
   }


  private function test_print($item, $key)
  {
         //replace the $item if it matches something
  }

}

It gives me the following error -

Warning:  array_walk() [function.array-walk]: Unable to call
 test_print() - function does not exist in ...

So, how do I specify $this->test_print() while using array_walk() ?

Thanks,
Sandeepan

+6  A: 

If you want to specify a class method as a callback, you need to specify the object it belongs to:

array_walk($fieldsArray, array($this, 'test_print'));

From the manual:

A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.

Check out http://www.ideone.com/oz3Ma to see this in action.

Daniel Vandersluis
Yes I tried this before but it gives me this error - `Warning: array_walk() [function.array-walk: Unable to call Array() - function does not exist in` However this is working `array_walk($fieldsArray,'user::test_print');`. So what is wrong. I wanted to use `$this`
sandeepan
What version of PHP?
tj111
Can you show the exact code that doesn't work (that issues that warning)?
ircmaxell
@tj111 PHP version 5.2.6
sandeepan
Oh I found the issue... please don't downvote guys... I did not initiate user object... was doing `user::getUserFields()`
sandeepan