Constructors

Getting Started with PHP
Getting Started with PHP : Home
Introduction
Installation
Hello World
Data Types in PHP
Variables in PHP
Operators in PHP
Decision Making in PHP
Iterations in PHP
Functions in PHP
Arrays in PHP
Strings in PHP
Object Oriented PHP
Classes and Objects
Constructors
Inheritance
Object Interfaces
Static and Final
Advanced Features in PHP
GET and POST
Session in PHP
Cookies in PHP
Server Variables

Constructor
Constructor is a method or function which is called when a new instance of a class is created i.e. a new object is created. Constructors are automatically called while creating new object.
We put those statements in constructors which we want to execute each time a new object is created.
Constructors are defined using __construct(args)(double underscore) function in a class.

<?php
 class car{
 	private $model; // properties
 	private $brand;
 	private $number;
 	
 	function __construct($modal,$brand,$number){ //Constructor
 		$this->modal = $modal;//Here $modal is a different variable
 							  // not the property of class
 		$this->brand = $brand;
 		$this->number = $number;
 	}

 	public function showcar(){
 		echo $this->modal."\n".$this->brand."\n".$this->number;
 	}
 }
 $car_A = new car("7S","Tes","BS 4202"); //creating new object
 						// and passing arguments to constructor
 $car_A->showcar(); // calling method to print car details

?>


Output
7S Tes BS 4202

Here we passed arguments for the intialization of values while creating new object.
It is not necessary to define a constructor. It's upto the developer's requirement.
Destructor
Destructor is also a method of class which is called when there is no reference to object is available.
Destructors are defined usnig __destruct() function.

Login to Track Your Progress