Summary: in this tutorial, you will learn how to initialize object’s properties using a constructor and clean up resources before PHP releases the object from the memory using a destructor.
PHP Constructor
When you create a new object, it is useful to initialize its properties e.g., for the bank account object you can set its initial balance to a specific amount. PHP provides you with a special method to help initialize object’s properties called constructor.
To add a constructor to a class, you simply add a special method with the name __construct()
. Whenever you create a new object, PHP searches for this method and calls it automatically.
The following example adds a constructor to the BankAccount class that initializes account number and an initial amount of money:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | php class BankAccount{ /** * bank account number * @var string bank account number */ private $accountNumber; /** * total balance * @var float total balance */ private $totalBalance; /** * inits bank account with a particular account no and * initial amount * @param string $accountNo * @param float $initialAmount */ public function __construct($accountNo, $initialAmount){ $this->accountNumber = $accountNo; $this->totalBalance = $initialAmount; } //... other methods in the below section } |
Now you can create a new bank account object with an account number and initial amount as follows:
1 2 | // create a new bank account object $account = new BankAccount('1243845355',2000); |
PHP constructor overloading
Constructor overloading allows you to create multiple constructors with the same name __construct()
but different parameters. Constructor overloading enables you to initialize object’s properties in various ways. The following example demonstrates the idea of constructor overloading:
1 2 3 4 5 6 7 8 9 10 11 | public function __construct(){ } public function __construct($accountNo){ $this->accountNumber = $accountNo; } public function __construct($accountNo, $initialAmount){ $this->accountNumber = $accountNo; $this->totalBalance = $initialAmount; } |
We have three constructors:
- The first constructor is empty, it does nothing.
- The second one only initializes account number.
- The third one initializes both account number and initial amount.
PHP have not yet supported constructor overloading, Oops. Fortunately, you can achieve the same constructor overloading effect by using several PHP functions.
Let’s take a look at the following example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | php class BankAccount{ /** * bank account number * @var string bank account number */ private $accountNumber; /** * total balance * @var float total balance */ private $totalBalance; /** * inits bank account with a particular account no and * initial amount * @param string $accountNo * @param float $initialAmount */ public function __construct(){ $args = func_get_args(); $num = func_num_args(); if(method_exists($this,$f = 'init_' . $num)) { call_user_func_array(array($this,$f),$args); } } public function init_1($accountNo){ $this->accountNumber = $accountNo; } public function init_2($accountNo,$initialAmount){ $this->accountNumber = $accountNo; $this->totalBalance = $initialAmount; } //... other methods in the below section } $a1 = new BankAccount('121412324', 2000); var_dump($a1); $a2 = new BankAccount('232321242'); var_dump($a2); |
How the constructor works.
- First, we get constructor’s arguments using the
func_get_args()
function and also get the number of arguments using thefunc_num_args()
function. - Second, we check if the
init_1()
andinit_2()
method exists based on the number of constructor’s arguments using themethod_exists()
function. If the corresponding method exists, we call it with an array of arguments using thecall_user_func_array()
function.
PHP destructor
PHP destructor allows you to clean up resources before PHP releases the object from the memory. For example, you may create a file handle in the constructor and you close it in the destructor.
To add a destructor to a class, you just simply add a special method called __destruct()
as follows:
1 2 3 | public function __destruct(){ // clean up resources here } |
There are some important notes regarding the destructor:
- Unlike a constructor, a destructor cannot accept any argument.
- Object’s destructor is called before the object is deleted. It happens when there is no reference to the object or when the execution of the script is stopped by the
exit()
function.
The following simple FileUtil
class demonstrates how to use the destructor to close a file handle. (Check it out the PHP File I/O tutorial to learn how to deal with files in PHP).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | php class FileUtil{ private $handle; private $filename; /** * inits file util with filename and mode * @param string $filename * @param string $mode */ public function __construct($filename,$mode){ $this->filename = $filename; $this->handle = fopen($filename, $mode); } /** * close the file handle */ public function __destruct(){ if($this->handle){ fclose($this->handle); } } /** * display file content */ public function display(){ echo fread($this->handle, filesize($this->filename)); } } $fu = new FileUtil('./test.txt', 'r'); $fu->display(); |
In this tutorial, we have introduced PHP constructor and destructor to help you initialize object’s properties and clean up resources before the object is deleted.