Calling Methods in the COnstructor

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Calling Methods in the COnstructor

Post by McGruff »

I wanted to find out if calling methods in the contructor is frowned on? I'm self-taught so who knows what bad habits I'm developing :)

I have a search class which puts all the common code in a parent and has childs to do everything else required to search a specific site area (forums, articles, news, calendar etc).

At present, all childs have a constructor which calls half-a-dozen-or-so parent/child functions to perform the search. An alternative would be to put all that in a function (external to the class definitions) which instantiates a child, runs parent constructor, etc in the required sequence.

Hope that makes sense.

Should constructors only be used to declare properties rather than call methods?
User avatar
nielsene
DevNet Resident
Posts: 1834
Joined: Fri Aug 16, 2002 8:57 am
Location: Watertown, MA

Post by nielsene »

A constructor should do everything required to create a valid object based on its arguments. If that means calling other functions, go right ahead. Many OOP Languages allow constructor overloading (ie different constructors with different numbers/types of arguments). In these languanges there will typically be a "default" no argument constructor that probably only initializes its attributes to default values, with other customized constructors for more specific/common creation tasks. These commonly are more complicated and often involved functional calls.

PHP, without constructor overloading (which can not be entirely simulated though default arguments), often ends up with simple "default" constructors because there is almost always a need for a simple "new Object()" with get/sets and other "configuration" functions defined later, but its not required.

Calling the parent class is definitely an OK thing to do, typically you'll alwasy at least call the parent constructor. I wouldn't suggest calling current class methods -- while PHP allows it, it also means that $this has not been properly initialized.....
Post Reply