Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to automaticly build variables from array?
    primarykey
    data
    text
    <p>I would like to instanciate a class, that takes any number of consturctor params.</p> <p>Lets say I have a class Man, that takes two arguments in constructor.</p> <pre><code>class Man { protected $name; protected $age; public function __construct($name, $age) { $this-&gt;name = $name; $this-&gt;age = $age; } } </code></pre> <p>Then I have params:</p> <pre><code>$params = array() $params['name'] = 'Jack'; $params['age'] = 55; </code></pre> <p>And this is how I instanciate a class:</p> <pre><code>$jack = new Man($params['name'], $params['age']); </code></pre> <p>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.</p> <p>So the only thing bothering me is how can I create variables automaticly? There is extract function but it returns the number of variables :(</p> <p>I would need something this:</p> <pre><code>$jack = new Man($name, $age); </code></pre> <p>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.</p> <p>The closest thing would be this:</p> <pre><code>$jack = new Man(extract($params)); </code></pre> <p>But extract function returns number, and i need to create variables from array, and give them to the class constructor.</p> <p>Edit:</p> <p>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.</p> <p>Thanks</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload