tags:

views:

69

answers:

4

Hi, I need some help here..

Is it possible to use PHP array_walk with an anonymous function (before PHP 5.3)? or some workaround..

I'm using array_walk inside a public class method and I don't want to define a PHP function.. I want to do something like:

array_walk($array, function($value) {...});

If that's not possible is it possible to use a class method instead of a function?


Thanks in advance,

Pedro

+4  A: 

Use create_function.

array_walk($array, create_function('&$v, $k', '$v...'));
Rocket
I totally forgot about this function. +1
NullUserException
Thanks... That's easier.. in array_walk documentation I couldn't found that example.. but now I realize that it is in "See Also".. Sometimes after hours and hours of programming our brain start burning =p
Pedro Gil
+1  A: 

It's possible using create_function().

Stolen from the manual:

<?php
$av = array("the ", "a ", "that ", "this ");
array_walk($av, create_function('&$v,$k', '$v = $v . "mango";'));
print_r($av);
?>
Pekka
Thanks... That's easier.. in array_walk documentation I couldn't found that example.. but now I realize that it is in "See Also".. Sometimes after hours and hours of programming our brain start burning =p
Pedro Gil
+1  A: 

To answer the second portion (the first has been answered well enough I think, although I never really liked create_function):

If that's not possible is it possible to use a class method instead of a function?

Yes, pass array($instance,'methodname') or array('classname','methodname') for object methods and static methods respectively.

Wrikken
+1  A: 

Yes, you can pass an array as second parameter, containing the object and the method name as string:

class Foo {
    public function a($a) {
         array_walk($a, array($this, 'b')); 
    }
    private function b($v, $k) {
         print $v;
    }
}

$f = new Foo();
$f->a(array('foo', 'bar'));

prints

foobar

The signature of the array_walk() (can be found in the documentation), defines the second argument as callback, for which the following description can be found:

A PHP function is passed by its name as a string. Any built-in or user-defined function can be used, except language constructs such as: array(), echo(), empty(), eval(), exit(), isset(), list(), print() or unset().

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

Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object at index 0.

Apart from common user-defined function, create_function() can also be used to create an anonymous callback function. As of PHP 5.3.0 it is possible to also pass a closure to a callback parameter.

Felix Kling