开发者

PHP anonymous function before 5.3 - array_walk

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 meth开发者_开发问答od instead of a function?


Use create_function.

array_walk($array, create_function('&$v, $k', '$v...'));


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜