|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2016-01-09 15:16 UTC] dharkness at gmail dot com
Description:
------------
I'm finding myself writing code like the following lately:
$titles = array_map(
function ($book) { return $book->getTitle(); },
$books
);
and
$anonymous = array_filter(
$books,
function ($book) { return $book->isAnonymous(); }
);
I was initially thinking a new callable form word work, e.g. [null, 'methodName'], but that by itself isn't callable and would not make sense when passed to other methods that accept callable such as call_user_func. The functions would either build a real callable using each array element or simply call the method directly on it.
$titles = array_map([null, 'getTitle'], $books);
and
$anonymous = array_filter($books, [null, 'isAnonymous']);
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sun Dec 07 21:00:01 2025 UTC |
After further consideration, perhaps this deserves new functions to avoid confusing the definition of a callable. They would behave just like these: function array_map_method(array $arr, $name) { return $arr ? array_map(function ($object) use ($name) { return $object->$name(); }, $arr) : array(); } and function array_filter_method(array $arr, $name) { return $arr ? array_filter($arr, function ($object) use ($name) { return $object->$name(); }) : array(); } May as well add array_map_property() and array_filter_property() for completeness. :)Hmm, wouldn't the newly introduced arrow functions offer a sensible alternative to your suggestion? For instance, $titles = array_map(fn($book) => $book->getTitle(), $books); Of course, still some boilerplate code, but a lot more flexible since properties can be read as well, for instance.