Reputation: 72672
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?
Upvotes: 1
Views: 488
Reputation: 9547
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.
Upvotes: 1
Reputation: 57234
It's impossible for a __construct()
to return anything because PHP returns a new instance of the class after the __construct() is called.
Upvotes: 1
Reputation: 43830
How about something like this.
$form = new myForm();
$form->element['fieldname'] = $form->createTextField('length'=>3);
myForm will extend the Form Class;
Upvotes: 3
Reputation: 70490
Even more so: whatever you return is discarded, and a new instance of the called object is just the return.
Upvotes: 4