class Dog {
protected $bark = 'woof!';
public function __get($key) {
if (isset($this->$key)) {
return $this->$key;
}
}
public function __set($key, $val) {
if (isset($this->$key)) {
$this->$key = $val;
}
}
}
What is the point of using these functions.
if i can use
$dog = new Dog();
$dog->bark = 'woofy';
echo $dog->bark;
Why would I bother declaring ‘bark’ as protected? Do the __get() and __set() methods in this case effectively make ‘bark’ public?
In this case, they do make
$this->barkeffectively public since they just directly set and retrieve the value. However, by using the getter method, you could do more work at the time it’s set, such as validating its contents or modifying other internal properties of the class.