PHP Constructor


A constructor is a special member method for automatic initialization of an object.


A constructor executed automatically whenever an object is created. And you have to provide the constructor name as same as the class name. It is a kind of member method and initializes an instance of the class. It has the same name as the class name and no return value.


The constructor can have any number of the parameters of the class may have a number of constructors overloaded.

Rules for Constructor:-

  • The constructor name must be the same as the class name.
  • It has no return type.
PHP Constructor

Syntax:

class class_name
{
		data_type member_data;
		member method();
        class_name() // constructor
        {
        	.........
        }
} 

Types of Constructor

  • Default constructor
  • Parameterized constructor

Default Constructor

A Constructor having no arguments is known as the Default constructor. The default constructor is invoked at the time of the creation.


Example:

 <?php
class Rectangle {
    public $length = 5;
    public $breadth = 6;
    public $area;

    // Default constructor
    public function __construct() {
        echo "Enter the length and breadth value: " . $this->length . " " . $this->breadth . "\n";
        $this->area = $this->length * $this->breadth;
        echo "Area of the Rectangle: " . $this->area . "\n";
    }
}

// Main execution
$r1 = new Rectangle();
?>

Parameterized Constructor

Constructor having the parameters(arguments) is known as the Parameterized constructor. Parameterized constructor is used to provide different values to the various objects.


Example:

 <?php
class Rectangle {
    public $length;
    public $breadth;
    public $area;

    // Parameterized constructor
    public function __construct($length, $breadth) {
        $this->length = $length;
        $this->breadth = $breadth;
        echo "Enter the length and breadth value: " . $this->length . " " . $this->breadth . "\n";
        $this->area = $this->length * $this->breadth;
        echo "Area of the Rectangle: " . $this->area . "\n";
    }
}

// Main execution
$r1 = new Rectangle(5, 6);
?>



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.