Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automaticly build variables from array?

Tags:

php

I would like to instanciate a class, that takes any number of consturctor params.

Lets say I have a class Man, that takes two arguments in constructor.

class Man
{
    protected $name;
    protected $age;

    public function __construct($name, $age)
    {
        $this->name = $name;
        $this->age = $age;
    }
}

Then I have params:

$params = array()
$params['name'] = 'Jack';
$params['age'] = 55;

And this is how I instanciate a class:

$jack = new Man($params['name'], $params['age']);

Now what I would like to achive is that params array can be of any size, 2, 3, 4, any, and class I would instanciate would have the same number of params.

So the only thing bothering me is how can I create variables automaticly? There is extract function but it returns the number of variables :(

I would need something this:

$jack = new Man($name, $age);

But this should be created automaticly. The script is only aware of the params array, and it needs to push all array values as variables.

The closest thing would be this:

$jack = new Man(extract($params));

But extract function returns number, and i need to create variables from array, and give them to the class constructor.

Edit:

I cant change the class Im building, my only goal is to construct that class, and pass variables it expects in constructor. So I have no power over the class Im building, my goal is to only instanciate that class, and gave her consturctor params. Those params are stored in $params array, but the class needs it as variables. Hope its easier to grasp what Im trying to achive.

Thanks

like image 498
Limeni Avatar asked Jul 16 '26 13:07

Limeni


1 Answers

You can do one of two things:

  1. Pass in an array of parameters:

    public function __construct(array $params) {}
    
  2. Use func_get_args() inside the function to get all of the arguments in the form of an associative array.

The first method is preferable, as it contains less "magic".

In order to call a function with an unknown set of arguments, when the arguments are in the form of an array you can use call_user_func_array().

like image 96
Madara's Ghost Avatar answered Jul 19 '26 03:07

Madara's Ghost



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!