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?
"Method" is basically just the name for a function within a class (or class function). Therefore __METHOD__ consists of the class name and the function name called ( dog::name ), while __FUNCTION__ only gives you the name of the function without any reference to the class it might be in.
Getters and setters are methods used to define or retrieve the values of variables, normally private ones. Just as the name suggests, a getter method is a technique that gets or recovers the value of an object. Also, a setter method is a technique that sets the value of an object.
PHP calls the __get() method automatically when you access a non-existing or inaccessible property. PHP calls the __set() method automatically when you assign a value to a non-existing or inaccessible property.
In this case, they do make $this->bark
effectively 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With