简体   繁体   English

PHP __get __set 方法

[英]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 ?为什么我会费心将“树皮”声明为protected Do the __get() and __set() methods in this case effectively make 'bark' public?在这种情况下,__ __get()__set()方法是否有效地公开了“吠叫”?

In this case, they do make $this->bark effectively public since they just directly set and retrieve the value.在这种情况下,它们确实使$this->bark有效地公开,因为它们只是直接设置和检索值。 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.但是,通过使用 getter 方法,您可以在设置时执行更多工作,例如验证其内容或修改 class 的其他内部属性。

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.基本上,我试图证明它们不必用作 object 属性的 getter 和 setter。

You would normally never leave those __get and __set exactly as you left it.您通常不会完全按照您离开的方式离开那些__get__set

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.使用__set可以做的另一个简单示例可能是更新数据库中的一行。 So you are changing something that isn't necessarily inside the class but using the class to simplify how it is changed/received.因此,您要更改的内容不一定在 class 内部,而是使用 class 来简化更改/接收的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM