如何在运行时正确取消 PHP 中的 class 属性?

How to properly unset a class property in PHP during runtime?

我有一个 class,它有一个 属性,我想在运行时 unset/destroy。 unsetting 发生在特定的方法中,但是调用它的方法 returns TRUEproperty_exists 中,而它不能直接访问 属性 和 $this->property因为它 returns 通知 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 returns TRUE 不应该发生,但 属性 未定义。

编辑

似乎如果 属性 是在 class' 架构中声明的,那么它就不能是 destroyed/unset(请参阅所选答案的演示),实际上它的行为自相矛盾:property_exists => 真,对象->属性 => 警告

但是当 属性 未定义但在对象构造时创建时,它可以取消设置并按预期运行。

从 PHP 5.3.0 开始,如果将其定义为对象变量,则 property_exists returns true 甚至在 unset 之后。在 unset.

之后使用 isset($this->isEmpty) 作为 returns false

查看差异:Demo

但是,您可能应该采取不同的方法,例如设置为 truefalsenull 或其他并检查它。