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?