Question

There's thousands of examples of php __get and __set out there, unfortunately nobody actually tells you how to use them.

So my question is: how do I actually call the __get and __set method from within the class and when using an object.

Example code:

class User{
public $id, $usename, $password;

public function __construct($id, $username) {
         //SET AND GET USERNAME
}

public function __get($property) {
    if (property_exists($this, $property)) {
        return $this->$property;
    }
}

public function __set($property, $value) {
    if (property_exists($this, $property)) {
        $this->$property = $value;
    }

    return $this;
}
}

$user = new User(1, 'Bastest');
// echo GET THE VALUE;

How would I set the values in the constructor and how would i get the value in the // echo GET THE VALUE;

Was it helpful?

Solution

This feature is called overloading in PHP. As the documentation states the __get or __set methods will be called if you are trying to access non existent or non accessible properties. The problem in your code is, that the properties your are accessing are existent and accessible. That's why __get/__set will not being called.

Check this example:

class Test {

    protected $foo;

    public $data;

    public function __get($property) {
        var_dump(__METHOD__);
        if (property_exists($this, $property)) {
            return $this->$property;
        }
    }

    public function __set($property, $value) {
        var_dump(__METHOD__);
        if (property_exists($this, $property)) {
            $this->$property = $value;
        }
    }
}

Test code:

$a = new Test();

// property 'name' does not exists
$a->name = 'test'; // will trigger __set
$n = $a->name; // will trigger __get

// property 'foo' is protected - meaning not accessible
$a->foo = 'bar'; // will trigger __set
$a = $a->foo; // will trigger __get

// property 'data' is public
$a->data = '123'; // will not trigger __set
$d = $a->data; // will not trigger __get
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top