[英]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.