PHP Basic Tutorial
MySQL Connection
PHP Advanced
PHP OOP
A constructor allows you to initialize an object's properties upon creation of the object.
A constructor is a special method in a class that is automatically called when a new object of the class is created.
In PHP, constructors are defined using the __construct() method.
class ClassName {
public function __construct() {
// Code that runs when an object is created
}
}
We see in the example below, that using a constructor saves us from calling the set_name() method which reduces the amount of code:
Try it yourself
Another example:
Try it yourself