在课堂a
上我有一个setter
定义。在b
扩展类的 classa
中,有一个private
变量,因此该类a
将无法看到。此代码中的setter
in 类a
永远不会将变量设置为test
不同于初始值的值,因为它无法访问它。如果您运行此代码,对于案例 A,它将输出0
.
但是,如果您运行案例 B,您将得到一个Exception
说法,即该属性test2
不存在。
<?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;
我的问题是,如果类a
实际上没有看到变量test
并且无法设置它的值,为什么我不会收到任何类型的错误、异常、警告甚至是一点点通知?
这是我在一个真实项目中刚刚发生的情况,由于没有生成错误并且代码在逻辑上看起来正确,因此很难找到。那么如何防止以后再犯这种错误呢?