Class return value to another function in same cla

2019-06-02 06:02发布

问题:

Im trying to learn how classes work and I found a problem. How do i pass a variable from a function to another function in same class? I tried using return but it didn't work.

Here is a simple class similiar with my problem:

class a
{

    function one()
    {

        $var = 5;
        return $var;

    }

    function two()
    {

        $this->one();

        if($var == 5){

            echo "It works.";

        }

    }

}

I just wrote that directly in here, so if there is any carelessness error just ignore it. So, how do I achieve this?

Thanks in advance! :)

P.S Sorry if this question has already been asked, Im very bad at searching.

回答1:

You're so close. You just need to capture the returned value from a::one() to use in a::two():

function two(){
    $var = $this->one();
    if($var == 5){
        echo "It works.";
    }
}

An alternative way is to use member variables in your class:

class a {
    private $var;

    function one(){
        $this->var = 5;
    }

    function two(){
        $this->one();
        if($this->var == 5){
            echo "It works.";
        }
    }
}