Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass variable number of variables to a class in PHP

Tags:

variables

php

I need to pass a variable number of strings to instantiate different classes. I can always do a switch on the size of the array:

switch(count($a)) {
case 1:
    new Class(${$a[0]});
    break;
case 2:
    new Class(${$a[0]}, ${$a[1]});
    break;
etc...

There has to be a better way to do this. If I have an array of strings ("variable1", "variable2", 'variable3", ...), how can I instantiate a Class without manually accounting for every possibility?

like image 398
user325282 Avatar asked Apr 25 '10 07:04

user325282


3 Answers

If you must do it this way, you can try:

$variable1 = 1;
$variable2 = 2;
$variable3 = 3;
$variable4 = 4;

$varNames = array('variable1', 'variable2', 'variable3', 'variable4');
$reflection = new ReflectionClass('A');
$myObject = $reflection->newInstanceArgs(compact($varNames)); 

class A
{
    function A()
    {
        print_r(func_get_args());
    }
}
like image 153
webbiedave Avatar answered Nov 18 '22 09:11

webbiedave


<?php

new Example($array);

class Example
{
    public function __construct()
    {
        foreach (func_get_args() as $arg)
        {
            // do stuff
        }
    }
}
like image 42
Amy B Avatar answered Nov 18 '22 09:11

Amy B


// Constructs an instance of a class with a variable number of parameters.

function make() { // Params: classname, list of constructor params
 $args = func_get_args();
 $classname = array_shift($args);
 $reflection = new ReflectionClass($classname);
 return $reflection->newInstanceArgs($args);
}

How to use:

$MyClass = make('MyClass', $string1, $string2, $string3);

Edit: if you want to use this function with your $a = array("variable1", "variable2", 'variable3", ...)

call_user_func_array('make', array_merge(array('MyClass'), $a));
like image 1
Lotus Notes Avatar answered Nov 18 '22 11:11

Lotus Notes