I am building a class and initially wanted to overload the constructs but discovered this is not allowed in PHP. My solution was using variable arguments for the one constructor. However, I am having some issues using string literals in a key => value pair and assigning the class properties. This leads me to ask my main question - is it actually possible to use variable variables to assign class properties via the constructor?
See example below:
class funrun{
protected $run_id;
protected $fun_id;
protected $funrun_title;
protected $date;
function __construct(){
if (func_num_args() > 0){
$args = func_get_args(0);
foreach($args as $key => $value){
$this->$key = $value;
}
$this->date = date();
function __get($name){
return $this->name;
}
function __set($name,$value){
$this->name = $value;
}
}
This seems to correctly assign the values. But then when I do the following:
$settings = array ('run_id' => 5, 'fun_id' => 3);
$fun_example = new funrun($settings);
echo $fun_example->run_id;
I get an error that the getter method isn't functioning:
Undefined property: funrun::$name
However, when I switch the class code to $this->key, the class property doesn't seem to be assigned at all. When I do $fun_example->$run_id, nothing is returned.
What am I missing here? Is there anyway to use an array with string literals to assign class properties? If not, what is a good way to tackle the variable argument issue with constructors?