Constructor in PHP

Sunday, 22 November 2026

A special function in class. Calls automatically when an object is created. __construct (two underscores) is fixed name for constructor. In PHP you can create only 1 constructor for each class.

class ConstructorDemo{
    function __construct(){
        echo "constructor called";
    }
}

$cd = new ConstructorDemo();

Output:

constructor called

Constructor is used for default values, database connections, etc.

Properties Declaration in PHP

In class variables are called Properties. Properties start with public keyword. Without public keyword you get error.

class Maths{
    public $value;
    //property declared
    public $value2 = 100;
}

Property usage in methods:

Functions inside class are called Methods. This is how properties are used in methods.

class Maths{
    //property declared but value is not assigned
    public $value;
    public $a = 0;
    //method declaration
    function sum($v){ 
        //property value assigned
        $this->value = 10;
        return $this->value + 10 + $v;
    }
}

$Obj = new Maths();
//calling method inside class, zero is function parameter
echo $Obj->sum(0); 
echo "
"; //calling public property that is inside class echo $Obj->a;

Output:

20
0

PHP OOPS Object Declaration

Any number of objects can be created from single class. Remember to add new keyword before class name and close with round braces. Object declaration comes outside class.

$obj = new Maths();
$obj2 = new Maths();
$cd = new Demo; // this is also correct for creating object

PHP Class Declaration

In class name declaration starting letter must be capital. Remember to add curly braces.

class Maths{

}