PHP __get __set方法

时间:2011-07-19 02:18:15

标签: php setter getter magic-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;
        }
    }
 }

使用这些功能有什么意义。

如果我可以使用

$dog = new Dog();
$dog->bark = 'woofy';
echo $dog->bark;

为什么我要将'bark'声称为protected?在这种情况下,__get()__set()方法是否有效地使'bark'公开?

3 个答案:

答案 0 :(得分:4)

在这种情况下,他们确实使$this->bark有效公开,因为他们只是直接设置和检索值。但是,通过使用getter方法,您可以在设置时执行更多工作,例如验证其内容或修改类的其他内部属性。

答案 1 :(得分:3)

不一定要与对象的属性一起使用。

这就是让他们变得强大的原因。

实施例

class View extends Framework {

    public function __get($key) {

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

    }
}

基本上,我试图证明它们不必仅用作对象属性的getter和setter。

答案 2 :(得分:1)

您通常不会完全离开那些__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可以执行的操作的另一个简单示例可能是更新数据库中的行。所以你正在改变一些不一定在类中的东西,而是使用类来简化它的更改/接收方式。

相关问题