I'm trying to use array_map to map the array to actual instances of my class.
class Pet {
private $petName;
public function __construct($args) {
$this->petName = $args['petName'];
}
}
$array = [['petName' => 'puppy'], ['petName' => 'kitty']];
$instances = array_map([Pet::class, '__construct'], $array);
However it ends in error:
non-static method Pet::__construct() cannot be called statically
Is it possible to pass constructor call as callback (beside wraping it in closure)?
Because it isn't the constructor that creates a class instance; the constructor is simply a block of code in the class that is magically called when a class instance is created using new
; so all you're doing is trying to call a non-static method of a class statically, which is the problem.
$instances = array_map(function($args) { return new Pet($args); }, $array);
is the only practical way of doing this
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With