I'm dumbfounded. I've been looking for a nice definition as to what a class constructor(specifically in PHP) exactly does.
As I understand it, it's the initial function that the class executes, when called, correct?
It is called whether or not we specifically call the function itself?
Can anyone shed some light here? Or at least point me in the right direction.
PHP allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.
A constructor creates an Object of the class that it is in by initializing all the instance variables and creating a place in memory to hold the Object.
For example you may want to initialize an integer variable to 10 or 20 based on a certain condition, when your class is created. In such a case you cannot hard code the value during variable declaration. such kind of code can be placed inside the constructor so that the initialization would happen when the class is instantiated.
When a PHP class is first called, the class will automatically run the class constructor function, which can help automatically configure the class. This can be useful if you need to preset some instance variables, sessions or cookies – prior to using the class methods.
A good read on Constructors in PHP
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