Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass argument in function?

Tags:

php

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?

like image 997
GusDeCooL Avatar asked Dec 12 '22 05:12

GusDeCooL


1 Answers

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);
}
like image 90
Vyktor Avatar answered Dec 26 '22 20:12

Vyktor