Question

I'm planning to log any modifications to certain properties of an object.

PHP has a magic method __set to overload any attempts to modify (private) properties from outside an object.

However, this does not apply from inside the object. Is there a way in PHP to have a generic setter function for any calls to modify a local propery of an object?


Example:

class Thing
{
  private $data;

  public function editData()
  {
    $this->data = 'edited';
  }

  function __magic($property, $value)
  {
    if ($property === 'data') {
      print 'Data is being edited!';
    }
  }

}

I would want the __magic function to be called before the $data is edited.

Was it helpful?

Solution

No, inside the object all the properties are accesible and don't need a magic method. But if you want to asign your properties throw a function, you only have to do a slighty modification in your code:

class Thing
{
  private $data;

  public function editData()
  {
    $this->propertySetter('data', 'edited');
  }

  function propertySetter($property, $value)
  {
    if ($property === 'data') {
      print 'Data is being edited!';
    }
    $this->$property = $value;

  }

}

OTHER TIPS

You could use __call like so:

public function __call($name, $args) {
    if(preg_match('/^set_/', $name)) {
       $attr = str_replace('set_', '', $name);
       $this->{$attr} = $args[0];
       if ($attr === 'data') {
          print 'Data is being edited!';
       }
    }
}

And in your constructor:

$this->set_data('edited');

EDIT

You can use a combination of __call and __set to get your functionality working.

public function __set($name, $value) {
  $this->{"set_$name"}($value);
}

This will allow you to execute set_attr when using object $obj->attr = '';

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top