I will try to explain what I want to accomplish with this method using an example:
You have an objectPerson
with the method getName()
which returns PersonName
.
Converting [PersonA, PersonB]
into [PersonNameA, PersonNameB]
.
I know PHP has a method array_column
to reach this with properties. But I am wondering if there is also a method to do this with objects' methods.
To expand on the usage of array_map()
that @axiax mentioned in his comment, you might feed it a closure for a first argument like this:
<?php
class Person
{
private $name;
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
$personA = new Person();
$personB = new Person();
$personA->setName('bob');
$personB->setName('alice');
$objects = [
$personA,
$personB
];
$names = array_map(
function(Person $p) {
return $p->getName();
},
$objects
);
var_dump($names); // ['bob', 'alice']