Q:

PHP programs to demonstrate the function returning object

belongs to collection: PHP Classes & Objects Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP Classes & Objects Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
<< PHP programs to pass an object of class as an argu...