<?php
interface Counter
{
/** @return self */
public function count();
/** @return int */
public function getCount();
}
class EchoingCounter implements Counter
{
private $counter;
public function __construct(Counter $counter)
{
$this->counter = $counter;
}
public function count()
{
echo __METHOD__ . "\n";
$this->counter->count();
return $this;
}
public function getCount()
{
echo __METHOD__ . "\n";
return $this->counter->getCount();
}
}
class ImmutableCounter implements Counter
{
private $count;
public function __construct($count = 0)
{
$this->count = (int) $count;
}
public function count()
{
return new ImmutableCounter($this->count + 1);
}
public function getCount()
{
return $this->count;
}
}
$counter = new EchoingCounter(new ImmutableCounter());
$counter = $counter->count()->count()->count()->count();
echo $counter->getCount();