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

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

Program/Source Code:

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.






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.