6.14.3 __set()This is NOT the latest copy of this book; click here for the latest version.
The __set() magic function complements __get(), in that it is called whenever an undefined class variable is set in your scripts. This is a little harder to use with good reason, however, and is more likely to confuse than help.
Here is one example of how you could use __set() to create a very simple database table class and perform ad hoc queries as if they were members of the class:
<?php
//...[snip - add your MySQL connection code here]...
class mytable {
public $Name;
public function __construct($Name) {
$this->Name = $Name;
}
public function __set($var, $val) {
mysql_query("UPDATE {$this->Name} SET $var = '$val';");
}
// public $AdminEmail = 'foo@bar.com';
}
$systemvars = new mytable("systemvars");
$systemvars->AdminEmail = 'telrev@somesite.net'; ?>
In that script $AdminEmail is commented out, and therefore does not exist in the mytable class. As a result, when $AdminEmail is set on the last line, __set() is called, with the name of the variable being set and the value it is being set to being passed in as parameters one and two respectively. This is used to construct an SQL query in conjunction with the table name passed in through the constructor. While this might seem like an odd way to solve the problem of setting key database values, it is pretty hard to deny that the last line of code ($systemvars->AdminEmail...) is actually very easy to read.
This system could be extended to more complicated objects as long as each object knows their own ID number.
Author's Note: By default, PHP lets you set arbitrary values in objects, even if their classes don't have that value defined. If this annoys you (if, for example, you used OPTION EXPLICIT in your old Visual Basic scripts) you can simulate the behaviour by using __get() and __set() to print errors.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|