Created
March 8, 2018 14:29
-
-
Save pwm/5d2b7cf33d22927c0344baefe0290052 to your computer and use it in GitHub Desktop.
Careful with immutability
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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