Advertisement
Google Ad Slot: content-top
PHP OOP - Constructor
What is a Constructor in PHP?
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.
Syntax of a Constructor
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:
Another example: