Php startup method when changing a property

Is it possible to run the php method when changing a property? As shown in the example below:

Grade:

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

An object:

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

Result:

  "MyProperty changed to 1" 
+6
source share
4 answers

Like @lucas, if you can set your property as private in the class, you can use __set () to detect changes.

 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. 
+5
source

You can achieve this best by using the setter method.

 class MyClass { private MyProperty; public function setMyProperty($value) { $this->MyProperty = $value; echo "MyProperty changed to " . $this -> MyProperty; } } 

Now you just call the setter, rather than setting the value yourself.

 $MyObject = new MyClass; $MyObject -> setMyProperty(1); 
+3
source

Using the magic __set method :

 class Foo { protected $bar; public function __set($name, $value) { echo "$name changed to $value"; $this->$name = $value; } } $f = new Foo; $f->bar = 'baz'; 

It might be better and more conditional to use the old old-fashioned setter instead:

 class Foo { protected $bar; public function setBar($value) { echo "bar changed to $value"; $this->bar = $value; } } $f = new Foo; $f->setBar('baz'); 
0
source

This post is pretty old, but I have to deal with the same problem and a typical class with multiple fields. Why use private properties? Here is what I implemented:

 class MyClass { public $foo; public $bar; function __set($name, $value) { if(!property_exists('MyClass', $name)){ // security return; } if ('foo' == $name) { // test on the property needed to avoid firing // "change event" on every private properties echo "Property " . $name . " modified"; } $this->$name = $value; } } $r = new MyClass(); $r->bar = 12; $r->foo = 1; //Property foo changed. var_dump($r); /* object(MyClass)[1] public 'foo' => int 1 public 'bar' => int 12 */ 
0
source

Source: https://habr.com/ru/post/1234602/


All Articles