<?php
final class CanNotSetProperties extends RuntimeException
{
public function __construct()
{
parent::__construct("You can not set properties on Immutable objects.");
}
}
final class ConstructorIsVisible extends RuntimeException
{
public function __construct()
{
parent::__construct("Immutable objects can not expose the constructor.");
}
}
final class CanNotBeCloned extends RuntimeException
{
public function __construct()
{
parent::__construct("Immutable objects can not be cloned.");
}
}
trait Immutable
{
final public function __set($property, $value)
{
throw new CanNotSetProperties;
}
final public function __clone()
{
throw new CanNotBeCloned;
}
final private function __construct()
{
throw new ConstructorIsVisible;
}
}
final class Test {
use Immutable;
}
$test = new Test;
$test->__construct();
Fatal error: Uncaught Error: Call to private Test::__construct() from global scope in /in/GDfWq:49
Stack trace:
#0 {main}
thrown in /in/GDfWq on line 49
Process exited with code 255.
Output for 8.3.2
Warning: Private methods cannot be final as they are never overridden by other classes in /in/GDfWq on line 45
Fatal error: Uncaught Error: Call to private Test::__construct() from global scope in /in/GDfWq:49
Stack trace:
#0 {main}
thrown in /in/GDfWq on line 49
Process exited with code 255.
Fatal error: Uncaught Error: Call to private Test::__construct() from invalid context in /in/GDfWq:49
Stack trace:
#0 {main}
thrown in /in/GDfWq on line 49
Process exited with code 255.