PHP Class Constructor and Destructor

PHP Class Constructor and Destructor

Instructor-svg Al-Mamun Sarkar
Apr 21 , 2021

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());

 

  • Share On:
  • fb
  • twitter
  • pinterest
  • instagram