tags:

views:

99

answers:

2

I am new to object oriented programming and writing some of my first classes for a PHP application.

In some of the simpler classes, I declare a function __construct(), and inside of that function, call certain class methods. In some cases, I find myself instantiating the class in my app, and not needing to do anything with the resultant object because the class's __construct() called the methods, which did their job, leaving me nothing left to do with the class.

This just doesn't feel right to me. Seems goofy that I have a new object that I never do anything with.

Again, I'll stress this is only the case for some of my more simple classes. In the more complicated ones, I do use class methods via the object and outside of __construct().

Do I need to rethink the way I coding things, or am I ok?

+4  A: 

Well, the constructor is used to create a new instance of a class, and to do any necessary setup on that class. If you're just creating the class and leaving it, that does seem a bit of a waste. Why not, for instance, use static functions in the class as an organizational tool and just call them(or a function that calls them) instead of constructing a new instance that you'll never use?

Annath
Damn, you beat me, I was just about to say the exact same thing. xD
musicfreak
Ha, that's been a recurring problem to me. I always get beaten to the questions that I can answer. :P I just got lucky for once! :D
Annath
+2  A: 

This just doesn't feel right to me. Seems goofy that I have a new object that I never do anything with.

Yes, that should raise a red flag.

In general, you should not let constructors have any side effects; They are meant for initialising the state of the object - not for anything else. There are of course exceptions to this rule, but in general it's a good guide line. You should also abstain from doing any heavy calculations in the constructor. Move that to a method instead.

Side effects are many things - Changes to global variables or static (class) variables; output to the environment (For example calls to print(), header() or exit()); calls to a database or other external service and even changes to the state of other objects.

A side effect free function is also called a "pure" function - as opposed to a procedure, which is a function that has side effects. It's a good practise to explicitly separate pure functions from procedures (and perhaps even label them as such).

troelskn