I have written this as I am learning OOP PHP. I have been having some trouble with passing variables' values to functions. but it turns out that the functions won't read the variables' values. Please see below and advise.
<?php
class calculator {
private $num1 = '1';
private $num2 = '2';
public function complete() {
return $num1 * $num2;
}
}
$calc = new calculator();
$result = $calc->complete();
echo $result;
You have to change this:
(With $this
you access the class property and not any variable)
public function complete() {
return $num1 * $num2;
}
to this:
public function complete() {
return $this->num1 * $this->num2;
//^^^^^ See here^^^^^
}
public function complete() {
return $num1 * $num2;
}
There is no variable $num1
or $num2
created in this function. Of course it does not "read the variables' values" .
What you want probably is:
public function complete() {
return $this->num1 * $this->num2;
}
Have you read the chapter about classes and objects in the PHP Manual?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.