我遇到了PHP中的类继承问题,我对原因和解决方法感到困惑。请看下面的代码:
class Vehicle {
public $properties = array();
public function funky($property) {
echo json_encode($this->properties) . PHP_EOL;
echo json_encode(isset($this->properties[$property])) . PHP_EOL;
echo json_encode($this->properties[$property]) . PHP_EOL;
}
}
class Car extends Vehicle {
public $properties = array('colour' => null, 'size' => null, 'fuel' => null);
}
$car = new Car();
$car->funky('colour');
打印:
{"colour":null,"size":null,"fuel":null}
false
null
如果我尝试使用此子类而不是使用非空值初始化数组:
class Car extends Vehicle {
public $properties = array('colour' => 'blue', 'size' => 8, 'fuel' => 'gas');
}
然后我实际上得到了我的期望:
{"colour":"blue","size":8,"fuel":"gas"}
true
"blue"
这对我来说没有意义。我的猜测是,如果子类使用null值初始化数组,那么它并不真正关心实际创建数组元素。但是,这与PHP似乎如何使用变量相冲突。例如:
$ar = array('takis' => null);
echo json_encode(isset($ar));
这打印“真实”! 对此有合理的解释吗?你会建议什么作为解决方法?
提前谢谢: - )
答案 0 :(得分:0)
true
,则 isset
会返回null
,否则会返回false
。
如果您需要检查数组索引是否存在而不管其值是否使用array_key_exists
。