Skip to content

Instantly share code, notes, and snippets.

@pwm
Created March 8, 2018 14:29
Show Gist options
  • Save pwm/5d2b7cf33d22927c0344baefe0290052 to your computer and use it in GitHub Desktop.
Save pwm/5d2b7cf33d22927c0344baefe0290052 to your computer and use it in GitHub Desktop.
Careful with immutability
<?php
declare(strict_types=1);
class X {
private $s;
public function __construct(string $s) { $this->s = $s; }
public function getS(): string { return $this->s; }
}
class Y {
private $x;
public function __construct(X $x) { $this->x = $x; }
public function getX(): X { return $this->x; }
}
$x = new X('foo');
$y1 = new Y($x);
$y2 = new Y($x);
assert(spl_object_hash($y1) !== spl_object_hash($y2)); // top object differ
assert(spl_object_hash($y1->getX()) === spl_object_hash($y2->getX())); // child object stay the same
$y1X = $y1->getX();
$data = (new ReflectionClass($y1X))->getProperty('s');
$data->setAccessible(true);
$data->setValue($y1X, 'bar');
assert($data->getValue($y1X) === $y1->getX()->getS()); // value is indeed changed
assert($y1->getX()->getS() === $y2->getX()->getS()); // and it also changed in the other
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment