一种方法中的设置器/获取器
只是一个想法:
示例(PHP): 设置名称: $object->name('name'); 获取名称: $对象->名称();
如果没有参数:该方法用作 getter,否则用作 setter。 对于简单的 getter/setter。 愚蠢,无论如何,也许?
编辑:跟进答案:我不太喜欢获取和设置,因为我更喜欢让界面尽可能明确。 当只有少数属性时,恕我直言,这也太过分了。 所以我想将其范围缩小到具有几个显式 getter/setter 的类/对象。
Just an idea:
example (in PHP):
to set name:
$object->name('name');
to get name:
$object->name();
If no argument: the method is used as getter, else as setter. For simple getters/setter. Stupid, whatever, maybe?
edit: to follow up on the answers: I don't really like get and set because I prefer to have the interface as explicit as possible. When there are only a few properties it's also overkill IMHO. So I'd like to narrow it down to classes/objects with a couple of explicit getters/setters.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可以使用 __call() 魔术方法来完成。
It can be done using the __call() magic method.
当然,如果它在您的应用程序中有意义,您可以这样做,否则我只会使用已经为您设置的标准 getter/setter。 你的函数可能看起来像这样:
Sure, you could do that if it makes sense in your application, otherwise I would just use the standard getters/setters which have already been set up for you. Your function could look something like this:
问题是很难遵循。 我更愿意使用 PHP5 的 __get 和 __set,这样获取和设置变量会更自然,而且每个人都会确切地知道我在做什么。 IE:
The problem is it would be hard to follow. I'd much rather use PHP5's __get and __set so it is more natural to get and set variables, and everyone would know exactly what I am doing. IE: