I found the following solution here in StackOverflow to get an array of a specific property of an object from an array of objects: PHP - Extracting a property from an array of objects
The proposed solution is to use array_map and inside create a function with create_function as follows:
$catIds = array_map(create_function('$o', 'return $o->id;'), $objects);
What happens ?: array_map runs through each element of the array in this case the stdClass object. First, he creates a function like this:
function($o) { return $o->id; }
He then calls this function on the object in the current iteration. It works, it works almost the same as this similar solution:
$catIds = array_map(function($o) { return $o->id; }, $objects);
But this solution only works in PHP version> = 5.3, because it uses Closure concept => http://php.net/manual/de/class.closure.php
Now the real problem:
The first solution with create_function increases memory because the created function will be written to memory and will not be reused or destroyed. In the second decision with Closure it will be.
Thus, the solutions give the same results, but have different behavior with respect to memory.
The following example:
// following array is given $objects = array ( [0] => stdClass ( [id] => 1 ), [1] => stdClass ( [id] => 2 ), [2] => stdClass ( [id] => 3 ) )
Bad
while (true) { $objects = array_map(create_function('$o', 'return $o->id;'), $objects); // result: array(1, 2, 3); echo memory_get_usage() ."\n"; sleep(1); } 4235616 4236600 4237560 4238520 ...
OK
while (true) { $objects = array_map(function($o) { return $o->id; }, $objects);
I spend so much time to find out, and now I want to know if this is a bug with the garbage collector or did I make a mistake? And why does it make sense to leave an already created and called function in memory when it will never be reused?
Here is an example: http://ideone.com/9a1D5g
Updated . When I recursively scan my code and its dependencies, for example. PEAR and Zend, I have too often found this BAD .
Updated . When two functions are nested, we proceed from within to evaluate this expression. In other words, it first runs create_function (once), and the return function name is an argument for a single call to array_map . But since the GC forgets to delete it from memory (no pointer is left for the function in memory), and PHP cannot reuse the function already in memory, let me think that there is an error, and not just the thing with "poor performance", This particular line of code is an example in PHPDoc and is reused in many large frameworks, for example. Zend and PEAR and more. With one line you can get around this "error", check. But I am not looking for a solution: I am looking for the truth. Is this a mistake, or is this my approach. And the last I could not decide.