PHP __get __set methods

旧时模样 提交于 2019-12-10 13:52:53

问题


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?


回答1:


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.




回答2:


The don't necessarily have to be used with the object's properties.

That is what makes them powerful.

Example

class View extends Framework {

    public function __get($key) {

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

    }
}

Basically, I am trying to demonstrate that they don't have to be used just as getters and setters for object properties.




回答3:


You would normally never leave those __get and __set exactly as you left it.

There are many ways that these methods might be useful. Here are a couple examples of what you might be able to do with these methods.

You can make properties read-only:

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
    }
}

You can do things with the data you have before actually getting or setting your data:

// ...
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);
    }
}

Another simple example of what you can do with __set might be to update a row in a database. So you are changing something that isn't necessarily inside the class but using the class to simplify how it is changed/received.



来源:https://stackoverflow.com/questions/6741595/php-get-set-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!