PHP Class Constructor and Destructor

Author: Al-mamun Sarkar Date: 2021-04-21 10:40:17

Constructor runs upon the creation of the object. We can pass parameters via the constructor. The destructor method runs at the end of the execution. That means it runs when all tasks of the object are done.

 

Syntax:

class ClassName 
{
	function __construct($parameter) {
	    
	}

	function __destruct() {
    	
  	}
}

 

Creating Class with Constructor:

class Vehicle 
{
	public $name;

	function __construct($name) {
	    $this->name = $name;
	}

	function display() 
	{
		echo "Vehicle Name is : {$this->name} 
";
	}

	public function getVehicleName() 
	{
		return $this->name;
	}

	function __destruct() {
    	echo "Everything is done";	
  	}
}

 

Creating Object:

$obj = new Vehicle("Car");
$obj->display();
print($obj->getVehicleName());