Tuesday, August 3, 2010

__set() & __get() Magic Methods

In the below example class Foo uses set and get methods while class Bar uses the magic methods. To summarise set and get, basically if you are trying to access a property of an object (and it has a get method) the name of the property you are requesting is passed into the get method and it can handle it how it wants. set works the same but it is only called when you attempt to assign a value to a member variable. The only difference being set takes two paramemters, the variable its setting and the value. 




class Foo{

    private $name;
    private $age;

    public function setName($name){
        $this->name = $name;
    }

    public function getName(){
        return $this->name;
    }

    public function setAge($age){
        $this->age = $age;
    }

    public function getAge(){
        return $this->age;
    }

}

$foo = new Foo();
$foo->setName("Dougal");
$foo->setAge(10);

echo $foo->getName(). " is " . $foo->getAge(). " years old\n";

class Bar{

    private $name;
    private $age;

    public function __set($var, $val){
        $this->$var = $val;
    }

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

}
$bar = new Bar();
$bar->name = "Dougal";
$bar->age = 10;

echo $bar->name . " is " . $bar->age. " years old";
?>

No comments:

Post a Comment