0

I'm aware of the existence of call_user_func_array, but I don't believe you can use this to construct a class (if you can, how do you do it?). As long as I'm not mistaken, how do you instantiate a class with an array as parameters?

for example:

class Test {
    public function __construct($var1, $var2) {
        // do something
    }
}

how would I instantiate it with this: array("var1_data", "var2_data")

1
  • Do you want to construct object with unknown number of arguments or a single argument which is an array ? Commented Nov 26, 2011 at 8:10

2 Answers 2

1
class Test {
    public function __construct(array $params) {
        // ...
    }
}

Don't use “magic” unless you really need it.

EDIT:

If what you need is varagrs, you can find an answer here.

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

1 Comment

I do need it, I'm obviously not using this for no reason.
0

If you must have multiple constructors, you should name them something other than __construct, then define a __construct method that can accept any number of arguments. Within that method, you can determine which of your custom constructors to use. If all you want to do is allow the constructor to be passed an array instead of a list of arguments, you can do it this way (note that this example lacks any error checking):

public function __construct() {
    $args = func_get_args();
    if(count($args) == 1 && is_array($args[0])) {
        $cArgs = $args[0];
    } else {
        $cArgs = $args;
    }

    __do_construct($cArgs[0], $cArgs[1]);

}

private function __do_construct($arg1, $arg2) {
    // do something
}

2 Comments

so I'm assuming there is no way to do this outside of the class?
Sure there is, I just assumed you were trying to do it within the class. You can do it with reflection. See http://stackoverflow.com/questions/1569949/instantiating-a-new-php-class-with-one-or-many-arguments.

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.