php - Simplify calling method on item in array_map

732

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?

729

Answer

Solution:

What you have looks okay to me.

The only other possible solution would be usingarray_column(), but it would only work if you declarename aspublic:

(PHP Version >= 7.0)

<?php

class Entity
{
    public $name = 'Alice';
    public function __construct(string $name) { $this->name = $name; }
};

$entities = [ new Entity('Alice'), new Entity('Bob') ];

var_dump(array_column($entities, 'name'));

Output

array(2) {

[0]=>

string(5) "Alice"

[1]=>

string(3) "Bob"

}

https://3v4l.org/VIVPU

946

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.

function getPropertyLambda($property) {
    return function($item) use ($property) {
        return $item->{'get' . ucfirst($property)}();
    };
}

$names = array_map(getPropertyLambda("name"), $entities);

People are also looking for solutions to the problem: php - How can i parse a date to same day of previous month?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.