In this tutorial, you can learn about how to use of PHP constructor and how to call the constructor inside a class
When you create an instance of the class, PHP automatically calls the constructor method.
A constructor allows you to initialize an object’s properties upon creation of the object. It is also called magic function of php, it is called as __construct()
See the below example
1 2 3 4 5 6 7 8 9 10 11 12 | <?php class ClassName { function __construct() { // initialize the object and its properties by assigning values } } ?> |
Basically, PHP has Three types of constructor
- Non-Parameterized constructor or Default Constructor
- Parameterized constructor
- Copy constructor
Non-Parameterized constructor or Default Constructor
It has no parameters, but the values to the default constructor can be passed dynamically.
Example-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?php class BankAccount { private $accountNumber; private $balance; public function __construct(){ // Some Code } public getAccountDetails($accountNumber,$balance){ $this->accountNumber = $accountNumber; $this->balance = $balance; } } |
Parameterized constructor
It takes the parameters, and also you can pass different values to the data members.
Example-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php class BankAccount { private $accountNumber; private $balance; public function __construct($accountNumber, $balance){ $this->accountNumber = $accountNumber; $this->balance = balance; } } $account = new BankAccount(101, 100000); |
Copy constructor
It accepts the address of the other objects as a parameter.
Questions asked in PHP Interview on Constructor
- What is a Constructor?
- How to call the Constructor?
- How many types of Constructor in PHP?
- What is a Destructor?