PHP program to initialize data members without using the constructor

Here, we are going to learn how to initialize data members without using the constructor in PHP?
Submitted by Nidhi, on November 10, 2020 [Last updated : March 13, 2023]

Initializing Data Members w/o using Constructor

Here, we will define a class Sample class with data members and then initialize private data members using the class method.

PHP code to initialize data members without using the constructor

The source code to initialize data members without using the constructor is given below. The given program is compiled and executed successfully.

<?php
//PHP program to initialize data members without
//using the constructor.
class Student
{
    //Attributes
    private $id;
    private $name;
    private $per;

    function Initialize()
    {
        $this->id = 0;
        $this->name = "";
        $this->per = 0.0;
    }

    function Display()
    {
        print ("Student Id  		  : " . $this->id . '<br>');
        print ("Student Name		  : " . $this->name . '<br>');
        print ("Student Percentage : " . $this->per . '<br>');
    }
}

$S = new Student();

$S->Initialize();
$S->Display();
?>

Output

Student Id : 0
Student Name :
Student Percentage : 0

Explanation

In the above program, we created a class Student that contains three data members $id, $name, and $per. Here, we created two methods Initialize() and Display().

The Initialize() method is used to initialize the data members of the class, here we used $this for data members.

The Display() method is used to print the values of data members on the web page.

After that, we created the object "$S" of the Student class and then called both methods.

PHP Class & Object Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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