-1

How to add two different variables within two different functions and store values into another variable inside another function. This my code: but i got output as 0 instead of 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();
?>
heart hacker
  • 431
  • 2
  • 8
  • 22

2 Answers2

2

before call third function you need to call first two functions that will assign values to $this->a & $this->b

try below code :

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();
Ranjit Shinde
  • 1,121
  • 1
  • 7
  • 22
1

Firstly, you are using object properties incorrectly. You need to first specify the scope of the property; in this case, I used protected scopes so you can extend the class as and when you need to use the properties directly.

Also, note if you're trying to add an unset variable, it will not work, you can either add this instance to your __construct() or set them to equal to 0 in the property instance.

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

}

This can then be used like this:

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

// todo: add logic

echo $s->avg();

Update:

Just side note, try not to output directly to a view in a method closure. Use templates, return the values from your methods and output them to a template.

Jaquarh
  • 6,493
  • 7
  • 34
  • 86