0

I am wondering if there is a way to watch for variable changes in PHP. For example let's say I have a class

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

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

Is there anyways to determine if a variable was changed?

1 Answer 1

9

Make this a private variable and then use the __set() magic method to filter all member variable value changes.

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

Sign up to request clarification or add additional context in comments.

4 Comments

How could I then get it?
That's pretty clever. __set runs for "inaccessible properties", and since it's "inaccessible" outside the class, it works ^~^
@JohnConde: Couldn't you also use __get()?
@RocketHazmat Yes, you can :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.