PHP Class Constructor function

What is the constructor function in a PHP class?

What is the Constructor of a Class?

The constructor of a class is a magical function or method that runs automatically as soon as an object of the class is created.

How to define or create the constructor in a PHP class?

There is a magic method called __construct() to define a constructor in PHP.

How to define a constructor?

It is very easy to define a constructor in PHP, like defining a normal function but, the function name must be the __construct.

Note: A class can have only one constructor, you can’t define multiple constructors in a single class.

<?php
class MyClass{
    function __construct()
    {
        echo "Hello From Constructor.\n";
    }
}

Constructor runs automatically as soon as an object is created

<?php
class MyClass{
    function __construct()
    {
        echo "Hello From the Constructor.\n";
    }
}

$obj1 = new MyClass();
Hello From the Constructor.

What If we create multiple objects of the same class?

In the following code, you can see that the object of MyClass is created twice.

Therefore the constructor of the MyClass will run two times. Because we have already read in the first paragraph that a constructor runs when an object is created.

<?php
class MyClass{
    function __construct()
    {
        echo "Hello From Constructor.\n";
    }
}

// First Object of the MyClass
$obj1 = new MyClass();

// Second Object of the MyClass
$obj2 = new MyClass();
Hello From Constructor.
Hello From Constructor.

Can we pass arguments to the constructor method in PHP?

Yes, you can pass arguments in a PHP constructor. Let’s see –

How to pass arguments to a PHP constructor?

You can pass arguments while creating an object of a Class.

When you create an object, you write the new keyword first, then the class name, and then parentheses (), and between these parentheses you can pass arguments for the constructor. Like – new ClassName(arg1, arg2, …)

Example 1
<?php
class MyClass{
    function __construct($name)
    {
        echo "Hello, $name";
    }
}

$obj1 = new MyClass('Mark');
Hello, Mark
Example 2
<?php
class MyClass{
    private $user_name;
    private $user_age; 

    function __construct($name, $age)
    {
        $this->user_name = $name;
        $this->user_age = $age;
    }

    function show(){
        echo "Name - {$this->user_name} & Age - {$this->user_age}";
    }
}

$obj1 = new MyClass('Mark', 24);
$obj1->show()
Name - Mark & Age - 24