PHP program to create an object of a class and access the class attributes

Here, we are going to learn how to create an object of a class and access the class attributes in PHP?
Submitted by Nidhi, on November 10, 2020

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

Program/Source Code:

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

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

$S = new Student();

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

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

Output:

Student Id : 101
Student Name : Rohit Kohli
Student Percentage : 78.23

Explanation:

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






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.