I’m stuck with a behaviour of PHP which I can’t seem to understand.
class A {
private $v;
public function __construct(&$v)
{
$this->v = &$v;
}
public function setV($v) {
$this->v = $v;
}
public function getV() {
return $this->v;
}
}
class B extends A {
public function setV($v) {
$this->v = $v;
}
}
$v = '1';
$c = new A($v); // <= this will be replaced
echo $c->getV() . "\n";
$v = '2';
echo $c->getV() . "\n";
$c->setV('3');
echo $c->getV() . "\n";
echo $v . "\n";
Outputs
1
2
3
3
But when I replace the object creation with $c = new B($v); it outputs
1
2
2
2
I would expect the same output as before. Why is this? I use PHP 5.3 but probably update to try to fix this.
When a class extends another parent class it can only use public and protected variables and functions from the parent class..
So this will print the same result ;