如何在两个不同的函数中添加两个变量并在php中将输出显示到另一个函数?

时间:2016-12-10 07:50:26

标签: php

如何在两个不同的函数中添加两个不同的变量,并将值存储到另一个函数中的另一个变量中... 这是我的代码:但是输出为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();
?>

2 个答案:

答案 0 :(得分:2)

在调用第三个函数之前,你需要调用前两个函数,这些函数将赋值给$ this-&gt; a&amp; $这 - &GT,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();

答案 1 :(得分:1)

首先,您正在错误地使用对象属性。您需要先指定属性的范围;在这种情况下,我使用了受保护的作用域,因此您可以在需要直接使用属性时扩展类。

另外,请注意,如果您尝试添加未设置变量,它将无效,您可以将此实例添加到__construct()或将其设置为等于0 in属性实例。

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();

<强>更新

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