`return $ this;`设计模式或反模式? [英] `return $this;` design pattern or anti-pattern?
问题描述
return $ this;
- 从我的角度来看:
-
Pro:似乎是相当不错的
模式风格,用于链接同一个对象上的许多操作,使您的代码更短。 -
Con:当您看到该对象在方法中返回自己的方法时,代码看起来有点奇怪,这样做会做些其他事情(例如某些属性的setter)
真的很好 pattern 练习或者可能是反模式实践?
编辑:好吧,从我这边称之为模式有点太多了,谢谢大家指出我的方向!
返回这个
允许您链接呼叫和设置值。配置某些对象非常有用(参见 Fluent界面)。你可以很容易地表达你想要的(你可以使用不同的返回类型来实现你想要的)。
I've seen many times Zend Framework using return $this;
pattern style
- and from my point of view:
Pro: seems its quite not bad
patternstyle for chaining many actions on the same object and making your code shorter.Con: code looks a bit weird when you see that object returns itself in the method, which does something else (e.g. setter for some property)
Is it really good pattern practice or maybe an anti-patternpractice?
EDIT: well it was a little too much from my side to call it "pattern", thanks everyone for pointing me to right direction!
Returning this
allows you to chain calls and set values. It is very useful for configuring some object (see Fluent interface). You can express very easily what you want (and you can use different return types to achieve what you want).
这篇关于`return $ this;`设计模式或反模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!