__set()

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) {
            GLOBAL $db;
            mysqli_query($db, "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 learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: __call() >>

Previous chapter: __get()

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.