I have a class with a structure as follows:
class Test {
private $var1;
private $var2;
private $var3;
public function __construct($params) {
foreach($params as $key => $value) {
$this->$key = $value;
}
}
}
The idea is that I can pass any number of parameters when instantiating a new object as I see fit. So for example I can do:
$params['var2'] = "Variable 2 Instantiated";
$params['var3'] = "Test";
$test = new Test($params);
Which would only instantiate $test->var2 and $test->var3.
Up until now, I’ve been writing a list of assignments, but if I want to instantiate an object with only half the available members, I have to check if values have been set etc.
SO the actual question is:
What is the correct syntax for assigning values to dynamic class members?
$this->$var = $var2
As per my example, is not working. I tried Googling with no luck.
Your example already works perfectly. See it working on codepad.org.