Is it possible to easily pass the individual items of an array to a method as parameters?
Like so:
Edit2:
I changed my code to show 'a solution', the problem with this solution is that it is deprecated since PHP 4.1 and removed in PHP 7.
<?php
$builder = new Builder;
$params = array('This is number: ', 4);
echo call_user_method_array('add', $builder, $params);
class Builder {
public function add($string1, $number1) {
return $string1 . $number1;
}
}
?>
Edit:
I made a mistake by using a simple example. The reason I am wondering whether this is possible is not for a function that returns a string like that. It is to create a MVC-like framework. The solution has to be all-round.
If you want to stick with your general solution, just use the proper non-deprecated method:
echo call_user_func_array([$builder, 'add'], $params);
Reference: callable
Demo: https://3v4l.org/4VFi6
Use implode() method.
<?php
$builder = new Builder;
$params = array('This is number: ', 4);
echo $builder->add($params); //returns 'This is number: 4'
class Builder {
public function add($params) {
return implode('', $params);
}
}
?>
Output
This is number: 4
Check Online Demo : Click Here
OR
Pass 2 parameters $params[0],$params[1].
<?php
$builder = new Builder;
$params = array('This is number: ', 4);
echo $builder->add($params[0],$params[1]); //returns 'This is number: 4'
class Builder {
public function add($string1 ,$number1) {
return $string1 . $number1;
}
}
?>
Online Demo : Click Here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With