PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
<?php
class test {
public $var;
public function __set($var, $val) {
$this->$var = $val . ' and was set by parent';
}
}
class testtwo extends test {
public $var2;
public function __set($var, $val) {
parent::__set($var, $val);
}
}
$testtwo = new testtwo;
$testtwo->var = 'hello';
$testtwo->var2 = 'hello';
echo('var is ' . $testtwo->var . '<br />');
echo('var2 is ' . $testtwo->var2);
?>
class test {
var $_data = array();
public function __set($var, $val) {
$this->_data[$var] = $val . ' and was set by parent';
}
public function __get($var) {
return $this->_data[$var];
}
}
class testtwo extends test {
}
$testtwo = new testtwo;
$testtwo->var = 'hello';
$testtwo->var2 = 'hello';
echo('var is ' . $testtwo->var . '<br />');
echo('var2 is ' . $testtwo->var2);
dayyanb wrote:Why doesn't it work for a normal variable?
Because __get() and __set() are really error handlers that are only called if a property is referenced that does not exist. If you create the property then any logic you have in __get()/__set() will not be called on second use of the property -- because it will then exist.
I thought I should use them because of a post in another thread:
If you're using PHP5, don't create a new function setVar(), overwrite the magic method __set() (which essentially does the same thing, but invoking it is cleaner).
arborint wrote:Yep. But don't forget that there are very good reasons for setters. The allow controlled access to variables.
Ok, thank you for your time. I am going to use normal set functions instead of Overloads. This situation seems rather hackish. I am actually creating a class to change information about a user. I am going to get the list of allowed variables directly from the columns in the mysql table and this would create problems if the column name was the same as a name of a variable in my class.