PHP OOP – Constructor
Constructor is a special type of method which automatically initialized upon creation of an object. A class constructor if defined is called whenever a program creates an object of that class.
Constructor method is invoked directly when an object is created from class.
Constructor has a special name in PHP that start with two underscore(__) followed by construct keyword.
Syntax: __construct()
Declaration of Constructors
function __construct() { // initialize the object and its properties by assigning // values }
The constructors is always defined in the public section of the class. Also, the values to properties of the class are set by Constructors.
Constructor types:
- Default Constructor – It has no any parameters, but we can pass values to the default constructor dynamically.
- Parameterized Constructor – It accepts the parameters. We can also pass different values to the data members.
- Copy Constructor – It accepts the address of the other objects as a parameter.
Let us understand, how constructor work by example –
<?php class Car{ public $name; function __construct($name) { $this->name = $name; } function get_name() { return $this->name; } } $car= new Car(Volkswagen"); echo $car->get_name(); ?> //OUTPUT Volkswagen
Another example :
<?php class Car{ public $name; public $color; function __construct($name, $color) { $this->name = $name; $this->color = $color; } function get_name() { return $this->name; } function get_color() { return "This car color is ". $this->color; } } $car = new Car("Volkswagen", "red"); echo $car->get_name(); echo "<br>"; echo $car->get_color(); ?> //OUTPUT Volkswagen This car color is red