1

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.

2
  • You may want to hang out at the function method for a while, until you fully understand how they "share variables", or, as a matter of fact, how they don't. Commented Nov 21, 2013 at 15:39
  • 1
    Your method one actually returns a value but there is nothing to receive it. You need to either store the result in a class member variable or a local variable inside the two method. Commented Nov 21, 2013 at 15:40

1 Answer 1

6

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.";
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Hah! Thanks alot for a great and fast answer! Cheers! I'll mark it as solution as soon as the timer goes down. :) Have a great day
Saw your edit, which one do you recommend? Which one is best in which environment?
They both will work well for you. I say use option 1. As you get more experience you'll see when to use option 2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.