简体   繁体   English

PHP函数不会选择变量的值

[英]PHP Function won't pick up variable's values

I have written this as I am learning OOP PHP. 我在学习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) (使用$this可以访问class属性,而不是任何变量)

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. 在此函数中没有创建变量$num1$num2 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? 您是否阅读过PHP手册中有关类和对象的章节?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM