PHP Tutorial

PHP Examples

PHP Practice

PHP program to implement the parameterized constructor using __construct()

Here, we are going to learn how to implement the parameterized constructor using __construct() in PHP?
Submitted by Nidhi, on November 19, 2020 [Last updated : March 13, 2023]

Parameterized Constructor Using __construct()

Here, we will create a class with data members and implement a parameterized constructor using __construct() to initialize data members.

Example of parameterized constructor using __construct() in PHP

The source code to implement the parameterized constructor using __construct() is given below. The given program is compiled and executed successfully.

<?php
//PHP program to demonstrate the parameterized constructor 
//using __construct().
class Sample
{
    private $num1;
    private $num2;

    public function __construct($n1, $n2)
    {
        $this->num1 = $n1;
        $this->num2 = $n2;
    }
    public function PrintValues()
    {
        echo "Num1: " . $this->num1 . "<br>";
        echo "Num2: " . $this->num2 . "<br>";
    }
}
$S = new Sample(10, 20);
$S->PrintValues();
?>

Output

Num1: 10
Num2: 20

Explanation

In the above program, we created a class Sample that contains data members $num1 and $num2. The Sample class contains a parameterized constructor using __construct() and a method PrintValues().

The parameterized constructor is used to initialized the data members, and PrintValues() method is used to print the values of data members.

$S = new Sample(10,20);

In the above statements, we created the object $S of Sample class then parameterized constructor of Sample class get called automatically and initialized the values of data members.

$S->PrintValues();

In the above statement, we called the PrintValues() method using object $S that will print the values of data members on the webpage.

PHP Class & Object Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.