How to pass an argument to a function?

i has such a function.

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 the property class, and the infinite arguments depend on the class they assigned.

another example, if I only set the $this->load method with 3 arguments, this will happen in the process

 function load($name, $arg1, $arg2){ $this->$name = new $name($arg1, $arg2); } 

can I do something like that?

+4
source share
5 answers

You can use a combination of func_get_args() , ReflectionClass and using this comment as follows:

 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); } 
+6
source

An easier way to handle this is to use an array for $arg variables. Other constructors, dynamically called ( new $name() ), then you need to accept the array as their input, and you can just go 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); } 
+3
source

If you do not specify default values ​​for the arguments, you must pass the values ​​when calling the function:

 function load($name, $arg1, $arg2, $arg3, $arg4){ load('x'); // fails, didn't specify args 1->4 

but with default settings:

 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 parameter 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 
+2
source

func_get_args () may be what you are 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 outputs:

 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 /> 
+1
source

There is a way to define a function with arguments of truly variable size in PHP. You need to use the func_get_args function in your function:

 function load() { $args = fnc_get_args(); $name = $args[0]; $arg1 = $args[1]; ... } 

Then you need to determine what / how to call next.

+1
source

Source: https://habr.com/ru/post/1396460/


All Articles