It's dangerous to go alone! Take $this

By Daniel Mason | 26 June 2013 | Comment


Because you're passing a reference to an object, rather than a whole object, there's negligible overhead doing this and it means you can chain methods together.

class SimpleCounter {

protected $total = 0;

public function add($amount)
    $this->total += $amount
    return $this
}

public function subtract($amount)
    $this->total -= $amount
    return $this
}

public function getTotal()
    return $this->total;
}
}

And now...

$counter = new SimpleCounter();
echo $counter->add(5)
->subtract(3)
->add(2)
->getTotal();
// 4
echo $counter->getTotal();
// 4

comments powered by Disqus