Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a class method as a callback function?

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()?

like image 485
Sandeepan Nath Avatar asked Oct 01 '10 14:10

Sandeepan Nath


People also ask

How do you define your callback method?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. The above example is a synchronous callback, as it is executed immediately.

How do you define a callback function in C++?

In simple language, If a reference of a function is passed to another function as an argument to call it, then it will be called as a Callback function. In C, a callback function is a function that is called through a function pointer. In C++ STL, functors are also used for this purpose.


1 Answers

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.

like image 120
Daniel Vandersluis Avatar answered Sep 20 '22 08:09

Daniel Vandersluis