A constructor is a special method inside a class that runs automatically when you create a new object. Its primary purpose is to initialise the object's properties with starting values, ensuring the object is ready to use immediately after it is created.
Key Features of Constructors
- Automatic Execution: The constructor is called automatically when an object is created using the
new keyword; you do not need to call it separately.
- Used for Initialisation: It sets up initial values for an object's properties.
- Only One Constructor: A class generally has one constructor method.
- No Return Value: A constructor does not return any value, not even void.
Defining a Constructor in PHP
In PHP 5 and later, constructors are defined using the method name __construct().
class Student {
public $name;
public $form;
// This is the constructor method
public function __construct($studentName, $studentForm) {
$this->name = $studentName;
$this->form = $studentForm;
}
public function introduce() {
echo "My name is $this->name and I am in Form $this->form.";
}
}
The keyword $this refers to the current object. $this->name means "the name property of this object."
Using the Constructor
When creating an object, you pass the initial values as arguments to the class:
$student1 = new Student("Amina", "Three");
$student1->introduce();
// Output: My name is Amina and I am in Form Three.
Worked Example: Bank Account
Consider a BankAccount class. When a new account is opened, the system must immediately know who owns the account and what the starting balance is. The constructor handles this automatically.
<?php
class BankAccount {
public $owner;
public $balance;
// Constructor to set initial values
public function __construct($accountOwner, $initialBalance) {
$this->owner = $accountOwner;
$this->balance = $initialBalance;
}
// Method to deposit money
public function deposit($amount) {
$this->balance += $amount;
echo "Deposited TZS $amount. New balance: TZS $this->balance <br>";
}
}
// Creating an object using the constructor
$myAccount = new BankAccount("Rehema", 10000);
$myAccount->deposit(5000);
?>
In this example, new BankAccount("Rehema", 10000) creates the object and runs the constructor immediately, setting the owner to "Rehema" and balance to 10,000.
Brief Note on Destructors
A destructor (__destruct()) is the opposite of a constructor. It is automatically called when an object is destroyed or goes out of scope (for example, when the script ends). It is commonly used for cleanup tasks, such as closing a file or releasing a resource.
Real-life application
In Tanzanian mobile money systems like M-Pesa, constructors are used when a new subscriber registers. For instance, when you sign up, the system creates a user object and uses a constructor to automatically set your phone number and initial balance to zero, making the account ready for deposits and withdrawals immediately.