PHP programs to demonstrate the function returning object

Here, we are going to demonstrate the function returning object in PHP.
Submitted by Nidhi, on November 21, 2020 [Last updated : March 13, 2023]

Function Returning Object in PHP

Here, we will demonstrate how we can return an object of a class from the function.

PHP code to demonstrate the example of function returning object

The source code to demonstrate the function returning object is given below. The given program is compiled and executed successfully.

<?php
//PHP programs to demonstrate the function returning object.
class Number
{
    public $Num;

    function __construct($n)
    {
        $this->Num = $n;
    }

    function Display()
    {
        echo "Num: " . $this->Num;
    }
}

function AddObj($obj1, $obj2)
{
    $temp = new Number(0);

    $temp->Num = $obj1->Num + $obj2->Num;

    return $temp;
}

$Obj1 = new Number(10);
$Obj2 = new Number(20);

$Obj3 = AddObj($Obj1, $Obj2);

$Obj3->Display();

?>

Output

Num: 30

Explanation

In the above program, we created a class Number that contains a data member $Num, parameterized constructor, and a Display() method.

The parameterized constructor is used to initialized the value of data members and the Display() method is used to display the value of data members on the webpage.

Here, we created a function AddObj() that accepts two object arguments and then adds the values of data members. Here we stored the result in a temporary object and return the temporary object.

At last, we created the two objects and passed the object into AddObj() function and then assigned the returned object to the $Obj3 after that called the Display() method that will print the value of data members on the webpage.

PHP Class & Object Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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