类返回值到同一类中的另一个函数 [英] Class return value to another function in same class

查看:149
本文介绍了类返回值到同一类中的另一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习类的工作方式,但发现了一个问题.如何将变量从一个函数传递到同一类中的另一个函数?我尝试使用return,但是没有用.

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?

提前谢谢! :)

P.S对不起,如果您已经提出了此问题,我的搜索非常不好.

推荐答案

您是如此亲密.您只需要捕获从a::one()返回的值即可在a::two()中使用:

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.";
        }
    }
}

这篇关于类返回值到同一类中的另一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆