简体   繁体   中英

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 ? Do the __get() and __set() methods in this case effectively make 'bark' public?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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