PHP Calling Methods using Array_Walk

This is post is now quite old and the the information it contains may be out of date or innacurate.

If you find any errors or have any suggestions to update the information please let us know or create a pull request on GitHub

The array_walk function is one of those unassuming little PHP functions that a lot of people may well ignore, but it is often very useful and can save writing out lines of code, compressing a pretty common coding structure into a single function call. Of course that also means that it is fast!

However, the standard documentation doesn’t make it clear if you can use array_walk on an array and use a class method as the callback rather than a global function. You can and here is how to do it:

$object = new MyClass;
$array = array(/* some array */);
array_walk($array, array($object, 'methodName'));

Tags: phparray_walkmethodsobjects