Skip to content

Instantly share code, notes, and snippets.

@mageekguy
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mageekguy/0bd0a5be9632ff1b62e0 to your computer and use it in GitHub Desktop.
Save mageekguy/0bd0a5be9632ff1b62e0 to your computer and use it in GitHub Desktop.
Immutability vs. mutability
<?php
interface console
{
function newData($data);
function noMoreData();
function dataGeneratorIs(dataGenerator $dataGenerator);
}
interface dataGenerator
{
function consoleIs(console $console);
}
class mutableConsole implements console
{
private
$data
;
function newData($data)
{
$this->data .= $data;
return $this;
}
function noMoreData()
{
echo $this->data . PHP_EOL;
}
function dataGeneratorIs(dataGenerator $dataGenerator)
{
$dataGenerator->consoleIs($this);
return $this;
}
}
class immutableConsole implements console
{
private
$data
;
function newData($data)
{
$console = new self;
$console->data = $this->data . $data;
return $console;
}
function noMoreData()
{
echo $this->data . PHP_EOL;
}
function dataGeneratorIs(dataGenerator $dataGenerator)
{
$dataGenerator->consoleIs($this);
return $this;
}
}
class numberGenerator implements dataGenerator
{
function consoleIs(console $console)
{
foreach (range(1, 10) as $number)
{
$console->newData($number);
}
return $this;
}
}
$numberGenerator = new numberGenerator;
(new mutableConsole)->dataGeneratorIs($numberGenerator)->noMoreData();
(new immutableConsole)->dataGeneratorIs($numberGenerator)->noMoreData();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment