Archive for February, 2009

Triggers within php objects using the __set() magic method

February 3, 2009

I don’t know if “trigger” is the right word for this behaviour, but if you want to automatically cause something to happen when an object variable is updated you can do so like this:

<?php
class classWithTrigger
{
    private $varOne = 0;
    private $varTwo = 0;

    public function __set($varName,$varValue)
    {
        $this->$varName = $varValue;
        if ($varName == "varOne") {
            $this->varTwo = $this->varOne * 9;
        }
    }

    public function __get($varValue)
    {
        return $this->$varValue;
    }
}

$test = new classWithTrigger;

echo $test->varOne; // Outputs 0
echo $test->varTwo; // Outputs 0

$test->varOne = 1;

echo $test->varOne; // Outputs 1
echo $test->varTwo; // Outputs 9

The __get() method gets called whenever an attempt is made (from outside the class) to get the value of an undefined or inaccessible (private or protected) variable – in this case it just returns the value as it would if the variable was public. Similarly, the __set() method gets called whenever an attempt is made (from outside the class) to set the value of an undefined or inaccessible variable. As you can see, you can use the fact that this gets called to trigger something, whether it’s an update to another object variable like here, or a DB update, or anything else you can think of.