Friday 21 May 2021

Php: __construct: Constructor method

__construct method is used to instantiate the properties of an object at the time of creation. __construct method is automatically called by php runtime at the time of object creation.

 

Syntax to define a constructor

public function __construct(arguments){

    .......

    .......

}

 

Find the below working application.

 

constructor_demo.php

#!/usr/bin/php

<?php

    class MyClass{
        public function __construct(){
            echo "I am in MyClass\n";
        }
    }

    echo "About to create an object of MyClass\n";
    $obj1 = new MyClass();

    echo "Object created\n";

?>

 

Output

$./constructor_demo.php 

About to create an object of MyClass
I am in MyClass
Object created

 

Constructor can take arguments

Example

public function __construct($id, $name, $age){

    $this->id = $id;

    $this->name = $name;

    $this->age = $age;

}

 

Above constructor method initialize id, name and age properties of an object.

 

Find the below working example.

 

constructor_arguments_demo.php

 

#!/usr/bin/php

<?php

    class Employee{
        public $id;
        public $name;
        public $age;

        public function __construct($id, $name, $age){
            $this->id = $id;
            $this->name = $name;
            $this->age = $age;
        }

        public function __toString(){
            return "id : $this->id\nname : $this->name\nage: $this->age\n";
        }
    }

    $emp1 = new Employee(1, 'Krishna', 31);
    $info = (string)$emp1;

    echo $info;

?>

Output

$./constructor_arguments_demo.php 

id : 1
name : Krishna
age: 31



 

 

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment