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 I do not want to declare "bark" as protected? Methods __get()and __set()in this case effectively make "bark" publicly available?

+5
source share
3 answers

In this case, they really become $this->barkpublicly available, as they simply set and retrieve the value. However, using the getter method, you can do more work at the time of its installation, for example, check its contents or change other internal properties of this class.

+4
source

.

.

class View extends Framework {

    public function __get($key) {

        if (array_key_exists($key, $this->registry)) {
            return trim($this->registry[$key]);
        }

    }
}

, , , .

+3

__get __set , .

. , .

:

protected $bark = 'woof!';
protected $foo = 'bar';

public function __get($key) {
    if (isset($this->$key)) {
        return $this->$key;
    }
}
public function __set($key, $val) {
    if ($key=="foo") {
         $this->$key = $val; //bark cannot be changed from outside the class
    }
}

- , :

// ...
public $timestamp;

public function __set($var, $val)
{
    if($var == "date")
    {
        $this->timestamp = strtotime($val);
    }
}

public function __get($var)
{
    if($var == date)
    {
        return date("jS F Y", $this->timestamp);
    }
}

, __set, . , , , , /.

+1

All Articles