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

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

Program/Source Code:

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.