简体   繁体   English

了解PHP的OOP魔术方法__set()和__get()

[英]Understanding PHP's OOP magic methods __set() and __get()

I am having difficulty understanding the magic methods in object oriented PHP - for example, __set() : 我很难理解面向对象的PHP中的魔术方法,例如__set()

<?php
class Post{
    private $name;

    public function __set($name, $value){
        echo 'Setting '.$name.' to <strong>'.$value.'</strong><br />';
        $this->name = $value;
    }
}

$post = new Post;
$post->name = 'Testing';
?>

This prints out: 打印输出:

Setting name to Testing 将名称设置为测试

What I am not understanding is why did $name change to "name" inside __set() ? 我不明白的是为什么$name会在__set()内更改为“ name”?

I would also like some explanation in plain English on how and why to use __set() and __get() . 我还想用简单的英语解释如何以及为什么使用__set()__get()

$name changed to $this->name , not to name . $name更改为$this->name ,而不是name In $this->name it is a property of object $this . $this->name它是对象$this的属性。

Normally you would never use __get() and __set() . 通常,您永远不会使用__get()__set() They can be used, for instance, in error handling to get access to an inaccessable or private properties, like your name property. 例如,它们可以用于错误处理中,以访问不可访问的属性或private属性,例如您的name属性。

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

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