简体   繁体   中英

PHP - Calling public function in class doesn't work

I'm new to working with classes in PHP

When I try to call $example->vars(); in the following class, the method changeVar() within this method vars() doesn't work. 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

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.

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