0

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
        )

)

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This is essentially using array_walk to change the original array instead of creating a new array with array_map. Are there any advantages of this?
@dave1010: no new memory allocated. while what you want is achieved here with better performance.:)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.