Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass constructor as callback

Tags:

php

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)?

like image 944
Jan Tajovsky Avatar asked Sep 05 '17 15:09

Jan Tajovsky


1 Answers

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

like image 135
Mark Baker Avatar answered Sep 25 '22 18:09

Mark Baker