Dynamically pass parameters to method, using method with variadic argument.

Category:
PHP
Tags:
PHP
variadic argument

Mohamed Jasir
6 months ago

Scenario : Call action() after confirming it
- Now action() could have any number of arguments
- Hence, while confirming we'll pass any number of arguments using variadic argument
- Then after confirming it, we'll call action() by validating first the number of parameters.
NOTE : We could go more further in validating parameters (i.e. type)
- This is one way to call a method with any number of parameters after confirmation.

/**
 * function with 3 arguments
 */
function action($one, $two, $three) {
	echo '<pre>';
	var_dump($one);
	var_dump($two);
	var_dump($three);
	echo '</pre>';
}

/**
 * function with variadic argument
 * NOTE : variadic argument stores passed parameters as an array
 * this will call action() by dynamically assigning its arguments
 */
function confirmAction(...$args) {
    // confirm it before calling actual action
	$reflection = new ReflectionFunction('action');
	if (count($args) >= $reflection->getNumberOfParameters()) {
		call_user_func_array('action', $args);
	}
}

// this will call action() with given arguments
confirmAction('one', 'two', 'three');

// this will call action() with first 3 arguments
confirmAction('one', 'two', 'three', 'four');

// this will NOT call action() as less arguments are provided
confirmAction('one', 'two');



DevZone
Made by developer, Made for developers