I have classes like this one:
class SomeObject
{
public function __construct($param1, $param2)
{
$this->process($param1, $param2);
}
...
}
So I can instantly "call" it as some sort of global function just like
new SomeObject($arg1, $arg2);
which has the benefits of
but might break unwritten rules of semantics by not waiting till a method is called.
Should I continue to feel bad because of a bad practice, or there's really nothing to worry about?
Clarification:
Example:
To give you an idea how I usually use this approach:
new Email('[email protected]', 'Subject line', 'Body Text');
I avoid to overuse it, of course, but in my opinion, this is really handy.
The most common mistake to do in a constructor as well as in a destructor, is to use polymorphism. Polymorphism often does not work in constructors !
Calling instance method in constructor is dangerous as the object is not yet fully initialized (this applies mainly to methods than can be overridden). Also complex processing in constructor is known to have a negative impact on test-ability.
A constructor is a special method of a class that initializes new objects or instances of the class. Without a constructor, you can't create instances of the class. Imagine that you could create a class that represents files, but without constructors, you couldn't create any files based on the class.
The invocation of a constructor constructs a new object of the class to which the constructor belong and returns a reference to the created object. The object is constructed by making use of the parameters passed to the constructor.
if the code in the constructor is part of creating and initializing the object for use, then I would put it there, but thats me personally, some people may disagree
however, it looks like what you are doing is not intended for building the object/class but doing some other process. this is bad, and should be done in a separate method.
Keep the constructor for construction.
This is a bad practice.
Using a constructor as a global function is not at all what it is intended for, and it would easily be confused. It is not easy to understand at all.
If you want a global function, declare one:
function myGlobalFunction(){ return $something; }
It really isn't that hard...
and even if you aren't using it as a function, you should use the constructor to do just that, construct an object. If you do more than that, you aren't using it for the right purpose, and future contributors will probably get confused quickly.
So, program in a way the makes sense. It really isn't that hard. A few extra keystroke can save you a lot of confusion.
If you need to always take certain actions after making a new instance of a class, try a factory:
class myFactory{
public static function makeObject(){
$obj = new Object();
$obj->init1();
return $obj;
}
}
$obj = myFactory::makeObject();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With