How to use callback functions from a class method

Cakephp, Codeigniter, Symphony, Kohana etc all these OOP framework. I feel comfort with cakephp for its wonderful features. BTW – you should be careful when you use callback function like array_filter, array_walk etc inside your code with OOP script, error/wrong may happen for new php programmer. Mistakenly you may call them in wrong way, lets consider the following codes –

function index(){
 $array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
 echo "Odd :\n";
 print_r(array_filter($array1, "odd"));
}

function odd($var)
{
    return($var & 1);
}

In the index method, we called callback function “odd”, that should be called as –

 print_r(array_filter($array1, array($this, "odd") ));

If you need to pass other parameter, this wont work. You need to try array_walk. Here is an example piece of code –

 print_r(array_walk($array1, array($this, "odd"), $param ));
Advertisements

4 thoughts on “How to use callback functions from a class method

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s