Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP __get __set methods

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?

like image 647
Nick Maroulis Avatar asked Jul 19 '11 02:07

Nick Maroulis


People also ask

What is __ method __ in PHP?

"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.

What is get and set method in PHP?

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.

What is __ get in PHP?

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.


1 Answers

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.

like image 103
Michael Berkowski Avatar answered Sep 22 '22 23:09

Michael Berkowski