Getter是一种获取一个属性的值的方法,Setter是一种设置一个属性的值的方法。可以为任何预定义的核心对象或用户自定义对象定义getter和setter方法,从而为现有的对象添加新的属性。
有两种方法来定义Getter或Setter方法:
在对象初始化时定义
在对象定义后通过Object的__defineGetter__、__defineSetter__方法来追加定义
在使用对象初始化过程来定义Getter和Setter方法时唯一要做的事情就是在getter方法前面加上“get”,在setter方法前面加上“set”。
还有一点要注意的就是getter方法没有参数,setter方法必须有一个参数,也就是要设置的属性的新值。
例如:
Getter是一种获取一个属性的值的方法,Setter是一种设置一个属性的值的方法。可以为任何预定义的核心对象或用户自定义对象定义getter和setter方法,从而为现有的对象添加新的属性。
有两种方法来定义Getter或Setter方法:
在对象初始化时定义
在对象定义后通过Object的__defineGetter__、__defineSetter__方法来追加定义
在使用对象初始化过程来定义Getter和Setter方法时唯一要做的事情就是在getter方法前面加上“get”,在setter方法前面加上“set”。
还有一点要注意的就是getter方法没有参数,setter方法必须有一个参数,也就是要设置的属性的新值。
例如: