PHP __get __set方法

Nic*_*lis 5 php getter setter 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;
        }
    }
 }
Run Code Online (Sandbox Code Playgroud)

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

如果我可以使用

$dog = new Dog();
$dog->bark = 'woofy';
echo $dog->bark;
Run Code Online (Sandbox Code Playgroud)

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

Mic*_*ski 4

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