Skip to content

Instantly share code, notes, and snippets.

@wilmoore
Created October 2, 2010 02:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilmoore/607198 to your computer and use it in GitHub Desktop.
Save wilmoore/607198 to your computer and use it in GitHub Desktop.
<?php
error_reporting(E_STRICT | E_ALL);
class ImmutableValueObject extends \ArrayObject
{
public function __construct(array $data = array(), $flags = \ArrayObject::ARRAY_AS_PROPS)
{
parent::__construct($data, $flags);
}
public function offsetSet($name, $value)
{
throw new \RuntimeException('This object is immutable');
}
public function offsetUnset($name)
{
throw new \RuntimeException('This object is immutable');
}
}
$f = new ImmutableValueObject(array('foo' => 'bar', 'baz' => 'bum'));
echo $f['foo'] . PHP_EOL;
echo $f->baz . PHP_EOL;
try {
$f['baz'] = 'bee';
} catch (\Exception $e) {
echo 'Exception thrown as expected' . PHP_EOL;
}
try {
$f->baz = 'bee';
} catch (\Exception $e) {
echo 'Exception thrown as expected' . PHP_EOL;
}
try {
$f->append('bee');
} catch (\Exception $e) {
echo 'Exception thrown as expected' . PHP_EOL;
}
try {
unset($f['baz']);
} catch (\Exception $e) {
echo 'Exception thrown as expected' . PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment