我有一个类,它有一个我想要在运行时取消设置/销毁的属性。取消设置发生在特定的方法中,但调用它的方法在property_exists
中返回TRUE
,而它不能直接使用$this->property
访问属性,因为它返回一个通知Notice: Undefined property:...
public function get(int $id) {
if ($record->data) {
$this->_transform($record); // Calling method that unsets prop
}
if (! property_exists($this, 'isEmpty') ) { // FALSE
$this->transform();
}else{
echo $this->isEmpty; // FALSE as well!
}
return $this;
}
private method _transform(Record $record) {
unset($this->isEmpty); // Unsetting happens here
return;
}
正如您在取消设置后的代码中所看到的,property_exists
返回TRUE,这是不应该发生的,但是该属性是未定义的。
编辑
似乎如果属性是在类的模式中声明的,那么它就不能被销毁/取消设置(参见selected answer的演示),而且实际上它的行为是矛盾的: property_exists => TRUE,object->property => warning
但是,如果属性没有定义,而是在对象构造时创建的,那么它就可以被取消设置并按照预期的方式运行。
发布于 2019-04-10 22:46:15
从PHP5.3.0开始,如果您将其定义为对象变量,那么即使在unset
之后,property_exists
也会返回true
。请改用isset($this->isEmpty)
,因为这在unset
之后返回false
。
查看差异:
但是,您可能应该采取一种不同的方法,比如设置为true
或false
或null
或其他值并进行检查。
https://stackoverflow.com/questions/55615108
复制相似问题