<?php
trait Immutable {
public function __construct()
{
//DO shit
var_dump("In trait constructor");
}
public function __set($name, $value) {
throw new Exception("can't touch this, nah nah nuh nahhh");
}
public function __get($name) {
return $this->$name;
}
}
class ImmutableThingy {
use Immutable;
protected $foo = 'bar';
public function __construct()
{
var_dump("In class constructor");
// What the fuck ever broh
}
}
$thing = new ImmutableThingy;
var_dump($thing, $thing->foo);
$thing->foo = 'baz';
var_dump($thing, $thing->foo);
string(20) "In class constructor"
object(ImmutableThingy)#1 (1) {
["foo":protected]=>
string(3) "bar"
}
string(3) "bar"
Fatal error: Uncaught Exception: can't touch this, nah nah nuh nahhh in /in/pR2YT:11
Stack trace:
#0 /in/pR2YT(35): ImmutableThingy->__set('foo', 'baz')
#1 {main}
thrown in /in/pR2YT on line 11
Process exited with code 255.
Output for 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
string(20) "In class constructor"
object(ImmutableThingy)#1 (1) {
["foo":protected]=>
string(3) "bar"
}
string(3) "bar"
Fatal error: Uncaught Exception: can't touch this, nah nah nuh nahhh in /in/pR2YT:11
Stack trace:
#0 /in/pR2YT(35): ImmutableThingy->__set('foo', 'baz')
#1 {main}
thrown in /in/pR2YT on line 11
Process exited with code 255.
Output for 5.5.0 - 5.5.38, 5.6.0 - 5.6.38
string(20) "In class constructor"
object(ImmutableThingy)#1 (1) {
["foo":protected]=>
string(3) "bar"
}
string(3) "bar"
Fatal error: Uncaught exception 'Exception' with message 'can't touch this, nah nah nuh nahhh' in /in/pR2YT:11
Stack trace:
#0 /in/pR2YT(35): ImmutableThingy->__set('foo', 'baz')
#1 {main}
thrown in /in/pR2YT on line 11
Process exited with code 255.