Is callback feedback possible in PHP5?
PHP functions such as "array_map" execute a callback, which can be a simple function or method of a class or object:
$array2 = array_map('myFunc', $array);
or
$array2 = array_map(array($object, 'myMethod'), $array);
But is there a syntax for passing a method that is bound to iterate over the current object (like 'invoke' in Prototype.js)? To be able to use the following:
$array2 = array_map('myMethod', $array);
with effect
foreach($array as $obj) $array2[] = $obj->myMethod();
Obviously, I can use this form, or I can write a wrapper function to make the call, and even do it inline. But since "myMethod" is already a method, it seems to be going around the house to do one of them.
source to share
function obj_array_map($method, $arr_of_objects) {
$out = array();
$args = array_slice(func_get_args(), 2);
foreach ($arr_of_objects as $key => $obj) {
$out[$key] = call_user_func_array(Array($obj, $method), $args);
}
return $out;
}
// this code
$a = Array($obj1, $obj2);
obj_array_map('method', $a, 1, 2, 3);
// results in the calls:
$obj1->method(1, 2, 3);
$obj2->method(1, 2, 3);
source to share
In principle, no. There is no specific syntax for this.
I can think of a more convenient way to do this in PHP 5.3 after seeing that there is always more than one thing in PHP, but I would argue that this is not necessarily better than your foreach example:
$x = array_reduce(
$array_of_objects,
function($val, $obj) { $val = array_merge($val, $obj->myMethod()); return $val; },
array()
);
Just go with your foreach :)
source to share
<?php
// $obj->$method(); works, where $method is a string containing the name of the
// real method
function array_map_obj($method, $array) {
$out = array();
foreach ($array as $key => $obj)
$out[$key] = $obj->$method();
return $out;
}
// seems to work ...
class Foo {
private $y = 0;
public function __construct($x) {
$this->y = $x;
}
public function bar() {
return $this->y*2;
}
}
$objs = array();
for ($i=0; $i<20; $i++)
$objs[] = new Foo($i);
$res = array_map_obj('bar', $objs);
var_dump($res);
?>
voila!
source to share
This is a slightly silly answer, but you can subclass ArrayObject and use that instead of a regular array:
<?php
class ArrayTest extends ArrayObject {
public function invokeMethod() {
$result = array();
$args = func_get_args();
$method = array_shift($args);
foreach ($this as $obj) {
$result[] = call_user_func_array(array($obj, $method), $args);
}
return $result;
}
}
//example class to use
class a {
private $a;
public function __construct($a) {
$this->a = $a;
}
public function multiply($n) {
return $this->a * $n;
}
}
//use ArrayTest instance instead of array
$array = new ArrayTest();
$array[] = new a(1);
$array[] = new a(2);
$array[] = new a(3);
print_r($array->invokeMethod('multiply', 2));
Outputs the following:
Array
(
[0] => 2
[1] => 4
[2] => 6
)
source to share