In class a
I have a setter
defined. In class b
, which extends class a
, there is a private
variable that the class a
will therefore not be able to see. The setter
in class a
in this code will never set the variable test
to a value different than the initial one, because it cannot reach it. If you run this code, for case A it will output 0
.
If you run case B however, you will get an Exception
saying that the property test2
does not exist.
<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
class a {
public function __set($prop, $value) {
if((!property_exists($this, $prop))) {
$className = get_called_class();
throw new Exception("The property `{$prop}` in `{$className}` does not exist");
}
$this->$prop = $value;
return true;
}
}
class b extends a {
private $test = 0;
public function getTest() {
return $this->test;
}
}
// Case A
$b = new b;
$b->test = 1;
echo $b->getTest();
// Case B
$b = new b;
$b->test2 = 2;
My question is, if the class a
doesn't actually get to see the variable test
and will not be able to set its value, why don't I get any kind of error, exception, warning or even a tiny little notice?
This is a situation that just happened to me in a real project and it was hard to find due to no error being generated and the code logically looking correct. So how do I prevent this kind of mistakes in the future?