Good day! Dear experts, please tell me - is it possible to intercept the change in behavior, already previously defined properties?

final class a { public $name = 'default'; } $a = new a; $a->name = 1; echo $a->name; // 1 

It is necessary to make it so that this property cannot be changed dynamically, but at the same time, so that it is public. Dynamic add-ons were able to be tracked, but already previously created I cannot understand how to intercept.

  • const NAME = 'default' - this option does not suit you? - Shadow33
  • excluded. Only properties - And
  • typo: behavior-> value. - Arnial

2 answers 2

You can use magic .

 final class A { private $_name = 'default'; public function __get( $name ){ if( $name === 'name' ) return $this->_name; } public function __set( $name, $value ){ if( $name === 'name' ){ echo "попытка установить значение для '$name' - игнорим\n" ; } } } $a = new A; $a->name = 1; // сообщение об игноре echo $a->name; // default 
  • At first I tried it did not work, but now it worked, strange! Problem solved! This option is working! - And

You can use the magic methods __get and __set

 final class a { private $_name = 'default'; function __set($property, $value) { if ($property == 'name'){ throw new Exception("You can't set value of propert"); } $this->property = $value; } function __get($property) { if($property == 'name'){ return $this->_name; } } } 

In principle, you can make full analogs of the properties https://habrahabr.ru/post/186420/