Skip to content

Instantly share code, notes, and snippets.

@macghriogair
Created October 1, 2018 11:20
Show Gist options
  • Select an option

  • Save macghriogair/ec30a876f4ec5e8a0301bd47453645b1 to your computer and use it in GitHub Desktop.

Select an option

Save macghriogair/ec30a876f4ec5e8a0301bd47453645b1 to your computer and use it in GitHub Desktop.
[Immutable] #valueobject #immutable
<?php
namespace Website\Traits;
trait ImmutableTrait
{
/** @var bool */
private $constructorWasCalled = false;
/**
* ImmutableTrait constructor.
* @throws \Exception
*/
public function __construct()
{
if (true === $this->constructorWasCalled) {
$this->throwImmutableException();
}
$this->constructorWasCalled = true;
}
/**
* @param $name
* @param $value
* @throws \Exception
*/
final public function __set($name, $value)
{
$this->throwImmutableException();
}
/**
* @throws \Exception
*/
final public function __clone()
{
$this->throwImmutableException();
}
/**
* @return void
* @throws \Exception
*/
final private function throwImmutableException()
{
throw new \Exception("The object is immutable.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment