Can somebody tell me why this is possible? An private attribute should only be changable from the class itself. s::$c is readable (getC()) but why I can write to it?
<?php
class s{
private $c;
public function __construct() {
$this->c = new t;
}
public function getC() {
return $this->c;
}
}
class t {
public $a = 1;
public $b = 2;
}
$x = new s();
$x->getC()->a = 5;
echo $x->getC()->a;
?>
Output: 5
when php returns an object it doesn’t duplicate it, it returns a pointer (reference) to the object in the memory.
therefore every change you make will affect the original object.
in order to prevent it you can clone the object before returning it