duancutan4770
duancutan4770
2013-11-21 15:37
浏览 84
已采纳

类返回值到同一个类中的另一个函数

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条回答 默认 最新

  • dphw5101
    dphw5101 2013-11-21 15:37
    已采纳

    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.";
            }
        }
    }
    
    点赞 评论

相关推荐