PHP Tutorial

PHP Examples

PHP Practice

PHP program to create multiple objects of a class and access attributes of the class

Here, we are going to learn how to create multiple objects of a class and access attributes of the class in PHP?
Submitted by Nidhi, on November 10, 2020 [Last updated : March 13, 2023]

PHP - Create Class's Multiple Objects, Access Its Attributes

Here, we will create a class Student and then create multiple objects of class and access all attributes of the class and then print the values attributes on the web page.

PHP code to create class's multiple objects, access its attributes

The source code to create multiple objects of a class and access the class attributes is given below. The given program is compiled and executed successfully.

<?php
//PHP program to create multiple objects of a class and access class attributes
class Student
{
    //Attributes
    public $id;
    public $name;
    public $per;
}

$S1 = new Student();
$S2 = new Student();

$S1->id = 101;
$S1->name = "Rohit Kohli";
$S1->per = 78.23;

$S2->id = 102;
$S2->name = "Virat Sharma";
$S2->per = 79.23;

print ("Student1:" . '<br>');
print ("--->Student Id  		  : " . $S1->id . '<br>');
print ("--->Student Name		  : " . $S1->name . '<br>');
print ("--->Student Percentage    : " . $S1->per . '<br>');

print ("Student2:" . '<br>');
print ("--->Student Id  		  : " . $S2->id . '<br>');
print ("--->Student Name		  : " . $S2->name . '<br>');
print ("--->Student Percentage    : " . $S2->per . '<br>');

?>

Output

Student1:
--->Student Id : 101
--->Student Name : Rohit Kohli
--->Student Percentage : 78.23
Student2:
--->Student Id : 102
--->Student Name : Virat Sharma
--->Student Percentage : 79.23

Explanation

In the above program, we created a class Student that contains three attributes $id, $name, and $per. After that, we created two objects of the Student class and then initialize the values of attributes and print the values of attributes for both objects using the print function on the webpage.

PHP Class & Object Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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