You are accessing the property incorrectly. With the syntax $this->$my_value = .. you set the property with the value name to $ my_value. Do you want $this->my_value = ..
$var = "my_value"; $this->$var = "test";
coincides with
$this->my_value = "test";
To fix a few things from your example, the code below is better than aproach
class my_class { public $my_value = array(); function __construct ($value) { $this->my_value[] = $value; } function set_value ($value) { if (!is_array($value)) { throw new Exception("Illegal argument"); } $this->my_value = $value; } function add_value($value) { $this->my_value = $value; } } $a = new my_class ('a'); $a->my_value[] = 'b'; $a->add_value('c'); $a->set_value(array('d'));
This ensures that my_value does not change its type to a string or anything else when you call set_value. But you can still set my_value direct because it is open. Last step: make my_value private and only access my_value using getter / setter methods
Philipp Feb 17 '13 at 10:41 2013-02-17 10:41
source share