PHP看变量?

时间:2013-12-06 16:37:32

标签: php

我想知道是否有办法观察PHP中的变量更改。例如,假设我有一个班级

class Chicken
{
    public $test = "hi";
}

$test = new Chicken();
$test->test = "hello"; // I want to know when this happens

是否有确定变量是否已更改?

1 个答案:

答案 0 :(得分:8)

将此变为私有变量,然后使用__set() magic method过滤所有成员变量值更改。

class Chicken
{
    private $test = "hi";

    public function __set($name, $value) {
      echo "Set:$name to $value";
      $this->$name = $value;
    }

    public function getTest() {
      return $this->test;
    }

    // Alternative to creating getters for all private members
    public function __get($name) {
      if (isset($this->$name)) {
        return $this->$name;
      }
      return false;
    }
}

$test = new Chicken();
$test->test = "hello"; // prints: Set: test to hello

See it in action