Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php run method on property change

Is it possible to run php method on property change? Like shown in the example below:

Class:

class MyClass
{
    public MyProperty;

    function __onchange($this -> MyProperty)
    {
        echo "MyProperty changed to " . $this -> MyProperty;
    }        
}

Object:

$MyObject = new MyClass;
$MyObject -> MyProperty = 1;

Result:

 "MyProperty changed to 1"
like image 838
Mohammad Avatar asked Oct 27 '15 11:10

Mohammad


1 Answers

Like @lucas said, if you can set your property as private within the class, you can then use the __set() to detect a change.

class MyClass
{
  private $MyProperty;

  function __set($name, $value)
  {
     if(property_exists('MyClass', $name)){
       echo "Property". $name . " modified";
     }
  }

 }


$r = new MyClass;
$r->MyProperty = 1; //Property MyProperty changed.
like image 177
Vishnu Nair Avatar answered Nov 06 '22 19:11

Vishnu Nair