PeeHaa
PeeHaa

Reputation: 72672

Is it ok for a construct to return something?

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

Answers (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.

Upvotes: 1

Xeoncross
Xeoncross

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

Ibu
Ibu

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

Wrikken
Wrikken

Reputation: 70490

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

Upvotes: 4

Related Questions