While going through the PHP code of one of my projects, I noticed something that - I thought - shouldn't work at all. And yet it doesn't result in any errors or notices in either PHP 5.2.17 or 5.6.14.
class Base {
private $privateVariable;
public function __construct() {
}
}
class Derived extends Base {
public function __construct() {
parent::__construct();
$this->privateVariable = 'Setting a private variable in the base class.';
}
}
$derived = new Derived();
How can this be? Why is PHP permitting Derived
to assign to a private variable defined in Base
?
Well, it turns out, it's not: the assignment to $this->privateVariable
in Derived
is creating a brand new member variable on Derived
called privateVariable
- which is completely independent from Base
's privateVariable
.
That wasn't my intention. Rather, it was a bug introduced when I lowered Base->privateVariable
's visibility, and didn't catch that derived classes were attempting to reference it.
Why isn't this an error? Does the PHP spec explicitly allow this?
Is there an error_reporting
value that will catch this?
Or is there some other automated way I can catch this?