Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Individual array items as parameters for method

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.

like image 944
kgongonowdoe Avatar asked May 25 '26 01:05

kgongonowdoe


2 Answers

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

like image 52
Yoshi Avatar answered May 26 '26 15:05

Yoshi


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

like image 40
RJParikh Avatar answered May 26 '26 14:05

RJParikh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!