Reputation: 5761
i have function like this.
function load($name, $arg1, $arg2, $arg3, $arg4){
$this->$name = new $name($arg1, $arg2, $arg3, $arg4);
}
the load()
method will load some class and set it as class property
and the infinite arguments, depend in the class they assigned.
another example if i only set method $this->load
with 3 argument, the this what will happen in the process
function load($name, $arg1, $arg2){
$this->$name = new $name($arg1, $arg2);
}
it is possible do something like that?
Upvotes: 4
Views: 204
Reputation: 57346
There is a way to define a function with a truly variable-size arguments in PHP. You need to use func_get_args
function in your function:
function load() {
$args = fnc_get_args();
$name = $args[0];
$arg1 = $args[1];
...
}
You'll need to then determine what/how to call next.
Upvotes: 1
Reputation: 11697
func_get_args() might be what you're looking for. From the PHP Docs:
<?php
function foo()
{
$numargs = func_num_args();
echo "Number of arguments: $numargs<br />\n";
if ($numargs >= 2) {
echo "Second argument is: " . func_get_arg(1) . "<br />\n";
}
$arg_list = func_get_args();
for ($i = 0; $i < $numargs; $i++) {
echo "Argument $i is: " . $arg_list[$i] . "<br />\n";
}
}
foo(1, 2, 3);
?>
The above example will output:
Number of arguments: 3<br />
Second argument is: 2<br />
Argument 0 is: 1<br />
Argument 1 is: 2<br />
Argument 2 is: 3<br />
Upvotes: 1
Reputation: 21007
You can use combination of func_get_args()
, ReflectionClass
and the help of this comment like this:
function load(){
$args = func_get_args();
if( !count( $args)){
throw new Something();
}
$name = array_shift( $args);
$class = new ReflectionClass($name);
$this->$name = $class->newInstanceArgs($args);
}
Upvotes: 6
Reputation: 270775
An easier way of handling this is to use an array for the $arg
variables. The other constructors dynamically called (new $name()
) would then need to accept an array as their input as well, and you can simply pass through the array of parameters:
// Params in an array
$params = array(1,2,3,4,5);
// Pass into the load() function
function load($name, $params) {
// And pass them through to the dynamic constructor
$this->$name = new $name($params);
}
Upvotes: 3
Reputation: 360882
Unless you set default values on the arguments, you must pass in values when the function is called:
function load($name, $arg1, $arg2, $arg3, $arg4){
load('x'); // fails, didn't specify args 1->4
but with defaults:
function load($name, $arg1, $arg2 = null, $arg3 = null, $arg4 = null){
load('x', 'y'); // works, args 2->4 are optional
load('x'); // fails, didn't specify arg1
load('x', 'y', 'z'); // works, args 3->4 are null.
There are other options - pass in option arguments in an array, or use func_get_arg()
function load($name) {
load('x', 'y', 'z') // not an error, use func_get_args/func_num_args to get the extras
Upvotes: 2