<?php
trait Immutable {
public function __set($name, $value) {
throw new Exception("Homie don't play dat");
}
public function __get($name) {
return $this->$name;
}
}
class ImmutableThingy {
use Immutable;
protected $foo = 'bar';
}
$thing = new ImmutableThingy;
var_dump($thing, $thing->foo);
$thing->foo = 'baz';
var_dump($thing, $thing->foo);
object(ImmutableThingy)#1 (1) {
["foo":protected]=>
string(3) "bar"
}
string(3) "bar"
Fatal error: Uncaught Exception: Homie don't play dat in /in/VCseE:5
Stack trace:
#0 /in/VCseE(23): ImmutableThingy->__set('foo', 'baz')
#1 {main}
thrown in /in/VCseE on line 5
Process exited with code 255.
Output for 5.5.0 - 5.5.38, 5.6.0 - 5.6.40
object(ImmutableThingy)#1 (1) {
["foo":protected]=>
string(3) "bar"
}
string(3) "bar"
Fatal error: Uncaught exception 'Exception' with message 'Homie don't play dat' in /in/VCseE:5
Stack trace:
#0 /in/VCseE(23): ImmutableThingy->__set('foo', 'baz')
#1 {main}
thrown in /in/VCseE on line 5
Process exited with code 255.