PHP __get __set 方法
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;
}
}
}
使用这些功能有什么意义。
如果我可以使用
$dog = new Dog();
$dog->bark = 'woofy';
echo $dog->bark;
为什么我要费心将“bark”声明为protected
?在这种情况下,__get()
和 __set()
方法是否有效地将“bark”公开?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这种情况下,他们确实使
$this->bark
有效地公开,因为他们只是直接设置和检索该值。但是,通过使用 getter 方法,您可以在设置时执行更多工作,例如验证其内容或修改类的其他内部属性。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.不一定必须与对象的属性一起使用。
这就是他们强大的原因。
示例
基本上,我试图证明它们不必仅仅用作对象属性的 getter 和 setter。
The don't necessarily have to be used with the object's properties.
That is what makes them powerful.
Example
Basically, I am trying to demonstrate that they don't have to be used just as getters and setters for object properties.
您通常不会将那些
__get
和__set
完全保留在您离开时的位置。这些方法有很多用途。以下是您可以使用这些方法执行的操作的几个示例。
您可以将属性设置为只读:
您可以在实际获取或设置数据之前对您拥有的数据进行操作:
使用
__set
可以执行的操作的另一个简单示例可能是更新 a 中的一行数据库。因此,您要更改的内容不一定在类内部,而是使用类来简化更改/接收的方式。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:
You can do things with the data you have before actually getting or setting your data:
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.