如何在php中将两个变量的值计算成不同的函数,并将输出显示到其他函数中?

如何在php中将两个变量的值计算成不同的函数,并将输出显示到其他函数中?,php,Php,如何在两个不同的函数中添加两个不同的变量,并将值存储到另一个函数中的另一个变量中。 这是我的代码:但我得到的输出是0,而不是30 <?php class race { var $a; var $b; function fast() { $a=10; $this->a; } function slow() { $b=20; $this->b;

如何在两个不同的函数中添加两个不同的变量,并将值存储到另一个函数中的另一个变量中。 这是我的代码:但我得到的输出是0,而不是30

<?php
class race
{
    var $a;
    var $b;

    function fast()
    {   
        $a=10;
        $this->a;
    }

    function slow()
    { 
        $b=20;
        $this->b;
    }

    function avg()
    {            
        $c=$this->a+$this->b;
        echo $c;
    }

}

$relay = new race();
$relay->avg();
?>

在调用第三个函数之前,您需要调用前两个将赋值给$this->a&$this->b的函数

请尝试以下代码:

protected $a;
protected $b;

function fast()
{   
    $a=10;
    $this->a = $a;
}
function slow()
{ 
    $b=20;
    $this->b = $b;
}
function avg()
{
    $c=$this->a+$this->b;
    echo $c;
}

}
$relay = new race();
$relay->fast();
$relay->slow();
$relay->avg();

首先,您使用的对象属性不正确。您需要首先指定属性的范围;在本例中,我使用了受保护的作用域,因此您可以在需要直接使用属性时扩展该类

另外,请注意,如果您试图添加一个unset变量,它将不起作用,您可以将此实例添加到
\u构造()
中,或者在属性实例中将其设置为等于0

class Speed {

    protected $_a = 0;
    protected $_b = 0;

    public function fast()
    {
        $this->_a = 20;
        return $this;
    }

    public function slow()
    {
        $this->_b = 10;
        return $this;
    }

    public function avg()
    {
        return $this->_a + $this->_b;
    }

}
然后可以这样使用:

$s = new Speed();
$s->fast()->slow();

// todo: add logic

echo $s->avg();

更新:


请注意,尝试而不是直接输出到方法闭包中的视图。使用模板,从方法返回值并将其输出到模板。

我没有问$this变量…你应该问
$this
。我问的是@Federkun not mine的功能性问题…如果我问错了…我真的很抱歉