简体   繁体   English

PHP - 在 class 中调用公共 function 不起作用

[英]PHP - Calling public function in class doesn't work

I'm new to working with classes in PHP我不熟悉 PHP 中的课程

When I try to call $example->vars();当我尝试调用$example->vars(); in the following class, the method changeVar() within this method vars() doesn't work.在以下 class 中,此方法vars()中的方法changeVar()不起作用。 Why can't I call this?为什么我不能调用这个?

<?php

class example {

    private $var1;

    public function __construct($var1) {
        $this->var1 = $var1;
    }
    
    public function changeVar() {
        $var1 = $this->var1;
        $var1 = $var1 + 1;
        return $var1;
    }
    
    public function vars() {
        $var1 = $this->var1;
        
        $var1 = 2;
        $var1 = $this->var1;
        echo "<br>made it here<br>";
        $var1 = changeVar(); // Calls function changeVar() from above. This step doesn't work?
        return $var1;
    }
}


$example = new example(1);
echo $example->changeVar(); // Echos 2
echo $example->vars(); // Should echo 3?
?> 

You need to call it like $this->changeVar() inside class您需要在 class 中将其称为$this->changeVar()

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

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