PHP:什么是 Getter 和 Setter?
PHP5 中的 getter 和 setter 是什么?
有人可以给我一个很好的例子并进行解释吗?
What are getters and setters in PHP5?
Can someone give me a good example with an explanation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是 OOP 中数据隐藏(或封装)的概念。例如,如果您想在类中拥有某个属性,让我们说“金额”,并为类的客户端提供更改或提取其值的选项,您应该将变量“金额”设置为私有(对于使用您的变量的人来说不可见)类)并生成两个方法,一个 getter 和一个 setter 来操作你的值(是公共的)。
原因是能够在设置或获取值之前验证数据或操作数据。这是一个简短的例子:
This is concept for data hiding (or encapsulation) in OOP. For example if you want to have a certain property in your class let's say 'Amount' and give the client of you class the option to change or extract its value You should make your variable 'Amount' private (not visible for those who use your class) and generate two methods a getter and a setter that manipulates your value (that are public).
The reason is to be able to validate data or manipulate it before setting or getting your value. Here is a brief example:
类的属性可以是私有的。这意味着只有对象可以读取和写入自己的私有属性。因此你需要方法来做到这一点。读取和返回属性值的方法称为 getter,写入属性的方法称为 setter。通过这些方法,类可以控制输出和输入的内容。这个概念称为 封装。
Attributes of classes can be private. That means only the object can read and write its own private attributes. Therefore you need methods to do that. The methods that read and return an attribute value are called getters and those that write attributes are called setters. With these methods the classes can control what’s going out and what’s coming in. This concept is called encapsulation.
Getters 和 Setters 是 PHP 5 中相当新的概念,以两个神奇函数 __get() 和 set() 的形式出现。这两个函数可以显着地设置或获取对象的属性值,如以下示例中所述。
Getters and Setters are quite new concept in PHP 5 in the form of two magical functions __get() and set(). These two functions set or get property value of an object dramatically as explained in the following example.
PHP 手册在这个问题上确实不是很详细,但是有一个非常详细的示例应该可以解释很多。 魔法方法:属性重载
The PHP manual is really not very verbose on the issue, but there is a very detailed example that should explain a lot. Magic methods: Property overloading