-3

PHP is an object oriented programming language, and it supports creating object of a class. But is there any way if I can pass a object of a class as the argument of a php function?

Example:

Note: This is not real application code, I have used this for an example.

This is my class.

class calculator{

    public $c;
    public $d;
    public function add($a, $b) : void {
       $c = $a+$b;
        $this->c = $c;
    }
    public function sub($a, $b) : void { 
        $d = $a-$b;
        $this->d = $d;
     }

  }

And here is the function where I want to pass the argument with the object.

function calculate_difference(calculator $cl){
            return $c - $d;
         }

And this where I am creating object of the class.

  $cal = new calculator();
  $cal->add(5,7);
  print $cal->c;  // Output is 12
  $cal->sub(3,2);
  print $cal->d; // Output is 1
  print calculate_difference($cal); //Output should be 11

The output of the calculate_difference function's result should be 11. But this is not working. It is showing me this Warnings.

Warning: Undefined variable $c in C:\xampp\htdocs\stackoverflow\index.php on line 88

Warning: Undefined variable $d in C:\xampp\htdocs\stackoverflow\index.php on line 88

So, how can I pass object as an argument of a php function please? Or what's wrong am I doing?

  • 4
    In short: Yes we can. But such a broad question is most certainly off-topic, which only underlines: Yes we can. – hakre Sep 24 '17 at 14:16
  • This of course begs the follow-up question: you must have tried this yourself before asking here. Did you run into some sort of problem? – rickdenhaan Sep 24 '17 at 14:28
  • In your example `calculate_difference` is not using the passed object e.g. it should do `$cl->c-$cl->d`. – apokryfos Jul 04 '23 at 11:11

2 Answers2

1

sure, you can pass the object variable as an argument. example:

$obj= new MyClass();
myFunction($obj);

this calls the function my function by passing the object $obj to it.

Milan Chheda
  • 8,159
  • 3
  • 20
  • 35
0

yes you can :

class test
{
   public  $a;
   public  $b;
}


function sums(test $test)
{
   echo $test->a + $test->b;
}

 $test = new test;
 $test->a = 5;
 $test->b = 2;

 sums($test);//output is 7
Mostafa Abedi
  • 541
  • 6
  • 19