note 108352 added to function.array-map

From: Date: Thu, 19 Apr 2012 07:01:45 +0000
Subject: note 108352 added to function.array-map
Groups: php.notes 
Request: Send a blank email to php-notes+get-187234@lists.php.net to get a copy of this message
I came up with a convenient syntax for method application, particularly useful inside the array_map. For instance, if you want to array_map(function($object, $arg1) { return $object->method($arg1, "arg2"); }, $objects, $args1); it is possible to provide a shorthand: global $_; // necessary inside a function, unfortunately array_map($_->method($_, "arg2"), $objects, $args1); Here's the implementation (works with 5.3) function m_caller($method) { $args = func_get_args(); array_shift($args); return function($object) use($method, $args) { global $_; $local_args = func_get_args(); array_shift($args); if(!is_object($object)) { // error } $reflection = new ReflectionMethod(get_class($object), $method); foreach($args as $key => $arg) { if($arg === $_) { $args[$key] = array_shift($local_args); } } return $reflection->invokeArgs($object, array_merge($args, $local_args)); }; } class MethodCaller { public function __call($name, $arguments) { return call_user_func_array('m_caller', array_merge(array($name), $arguments)); } public function __get($name) { return m_caller($name); } }; $_ = new MethodCaller(); ---- Server IP: 69.147.83.197 Probable Submitter: 91.221.27.122 ---- Manual Page -- http://www.php.net/manual/en/function.array-map.php Edit -- https://master.php.net/note/edit/108352 Del: integrated -- https://master.php.net/note/delete/108352/integrated Del: useless -- https://master.php.net/note/delete/108352/useless Del: bad code -- https://master.php.net/note/delete/108352/bad+code Del: spam -- https://master.php.net/note/delete/108352/spam Del: non-english -- https://master.php.net/note/delete/108352/non-english Del: in docs -- https://master.php.net/note/delete/108352/in+docs Del: other reasons-- https://master.php.net/note/delete/108352 Reject -- https://master.php.net/note/reject/108352 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#187234) next »