Is it ok for a construct to return something?

僤鯓⒐⒋嵵緔 提交于 2019-12-24 05:57:35

问题


The case:

I have a form class which handles HTML forms, cleans up fields and validates.

I'm thinking about creating separate classes for the different form fields, e.g.: text / file / select / etc.

The way I'm considering to use this is something like the following:

$form = new Form();
$form->element['fieldname'] = new HtmlTextField('length'=>3);

However someone here on SO told me once that a class construct should never return anything.

In the above case it would return the form field.

Is it correct that a __construct() should never return anything?


回答1:


Even more so: whatever you return is discarded, and a new instance of the called object is just the return.




回答2:


How about something like this.

$form = new myForm();
$form->element['fieldname'] = $form->createTextField('length'=>3);

myForm will extend the Form Class;




回答3:


It's impossible for a __construct() to return anything because PHP returns a new instance of the class after the __construct() is called.




回答4:


The constructor of a class cannot return anything other than an instance of this class when you return something else, this cannot be passed but is discarded. In your code it seems that this is what you want to have or I misunderstood you.



来源:https://stackoverflow.com/questions/6821288/is-it-ok-for-a-construct-to-return-something

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!