1

Possible Duplicate:
PHP __get and __set magic methods

I have an exam question on Get/Set methods, but I can not find any straight definitions. Could someone please explain/define it for me or just answer this question;

Identify and describe the two in-built "magic" methods used in PHP to retrieve and update private class/object properties.

Thanks.

Community
  • 1
  • 1
Remi Bond
  • 77
  • 1
  • 9

1 Answers1

4

The basic idea is this: If you call $foo->bar, where bar was never defined as a property for that class, it will be sent to the get/set magic methods. If you implement these methods, you will then be able to see the name that was called, and in the case of 'set', what value was passed. You can then do whatever you want with it

Example:

public function __set($name, $value)
{
    if ($name === "bar")
    {
        $this->privateProperty = $value;
    }
}

public function __get($name)
{
    if ($name === "bar")
    {
        return $this->privateProperty;
    }
}
JoeCortopassi
  • 5,023
  • 6
  • 35
  • 64