Q:

PHP program to initialize data members without using the constructor

belongs to collection: PHP Classes & Objects Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP Classes & Objects Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
PHP program to print the size of the empty class... >>
<< PHP program to define methods within the class...