`return $ this;`设计模式或反模式? [英] `return $this;` design pattern or anti-pattern?

查看:160
本文介绍了`return $ this;`设计模式或反模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到很多次Zend框架使用 return $ this; pattern style
- 从我的角度来看:




  • 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 pattern style 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆