dave1010
dave1010

Reputation: 15435

Instantiate all items in an array as objects of a class in PHP

I have an array of variables that are passed to a constructor of a class. I want to convert this into an array of objects of a specific class.

What's the best way to do this?

E.g.

class Foo { public function __construct($a) {$this->a=$a;} }
print_r(mass_instantiate(array(1, 2, 3), 'Foo'));

// gives:

Array
(
    [0] => Foo Object
        (
            [a] => 1
        )

    [1] => Foo Object
        (
            [a] => 2
        )

    [2] => Foo Object
        (
            [a] => 3
        )

)

Upvotes: 0

Views: 98

Answers (2)

Vipin Jain
Vipin Jain

Reputation: 1402

Use Array walk:

$arr = array(1,2,3,4,5,6,7,8,9,10);
array_walk($arr, 'init_obj');

function init_obj(&$item1, $key){
    $item1 = new Foo($item1);
}
print_r($arr);

this will give you the required output.

Upvotes: 1

dave1010
dave1010

Reputation: 15435

This is what I'm currently using. It's limited in that you can only pass 1 argument

/**
 * Instantiate all items in an array
 * @param  array $array of $classname::__construct()'s 1st parameter
 * @param  string $classname to instantiate
 * @return array
 */
function mass_instantiate($array, $classname)
{
    return array_map(function($a) use ($classname) {
        return new $classname($a);
    }, $array);
}

Upvotes: 0

Related Questions