Home »
PHP »
PHP programs
PHP programs to pass an object of class as an argument
Here, we are going to learn how to pass an object of class as an argument in PHP?
Submitted by Nidhi, on November 21, 2020 [Last updated : March 13, 2023]
Passing an Object as an Argument
Here, we will demonstrate how we can pass an object as an argument to the non-member function?
PHP code to demonstrate the example of passing an object of class as an argument
The source code to pass an object of class as an argument is given below. The given program is compiled and executed successfully.
<?php
//PHP programs to pass an object of class as an argument.
class Student
{
public $Id;
public $Name;
}
function Set(Student $S, $id, $name)
{
$S->Id = $id;
$S->Name = $name;
}
function Display(Student $S)
{
printf("Id : " . $S->Id . "<br>");
printf("Name: " . $S->Name . "<br>");
}
$S = new Student();
Set($S, 101, "Rahul");
Display($S);
?>
Output
Id : 101
Name: Rahul
Explanation
Here, we create a class Student that contains two data members Id and Name. After that we defined two function Set() and Display(). Here, we passed the object as an argument in both functions.
The Set() function is used to set the values of the data member of class Student, and Display() function is used to print the values of data members on the webpage.
At last, we created object $S of Student class then we called both Set() and Display() functions.
PHP Class & Object Programs »