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.

Advertisements

One Response to “Triggers within php objects using the __set() magic method”

  1. Kae Verens Says:

    hmm… I can think of handy uses for this! I’ve been recently trying to cut down the number of DB updates that I make outside of my classes, and this could be one more weapon in the arsenal.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: