简体   繁体   中英

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?

Eg

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
        )

)

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM