php - Simplify calling method on item in array_map
Suppose that we have a class representing an entity knowing its name:
class Entity
{
private $name;
public function __construct(string $name) { $this->name = $name; }
public function getName() :string { return $this->name; }
}
and we have an array of such entities:
$entities = [ new Entity('Alice'), new Entity('Bob') ];
What we really want is array of their names, so we usearray_map
function:
$names = array_map(
function($entity) { return $entity->getName(); },
$entities
);
But even though I removed type hints from the closure, the syntax still looks bulky to me, especially while knowing about[ $object, 'methodName' ]
closure syntax.
Is there a way to simplify the array_map construction?
Answer
Solution:
What you have looks okay to me.
The only other possible solution would be using
array_column()
, but it would only work if you declarename
aspublic
:(PHP Version >= 7.0)
Output
https://3v4l.org/VIVPU
Answer
Solution:
There is currently no shorter syntax for this. There are two RFC's (https://wiki.php.net/rfc/arrow_functions, https://wiki.php.net/rfc/short-closures), which want to introduce short closures, but they are still in draft and it's difficult to get a 2/3 majority for such features in php. In the near future I wouldn't expect them to apear in the language.
If you need a cleaner syntax for this case, you could create your own lambda generator.