0
votes

If I understand correctly, with __set() you can create class variables on the fly, which will be public, as well as access private/protected properties.

It seems like using:

__set($name,$value) {
  $this->data[$name] = $value;
}

OR:

__set($name,$value) {
  $this->$name = $value;
}

... would both result in all kinds of garbage in and out.

With individual setters (mutators), 1 for each protected/private property, you have individual validation control, but you have to write a bunch of setters.

Is there some way to take advantage of magic __set() and still validate depending on the property.

E.g. let's say

class stuff {

  private $name; // alphabet, limit 10 chars
  private $size; // integers 1 - 10;
  private $price; // decimals 0.000 - 999.999

  __set($property,$value) {
    $this->$property = $value;
  }

}

$thing = new stuff();
$thing->name = 1234;
$thing->size = 'b';
$thing->price = -40;

How would you validate the bad assignments?

2
An opinion rather than anything I can backup, but I try to avoid the magic methods. Also, if you need custom logic for a property, you might as well make a setter. That provides a convenient location for the logic.Corbin
I was thinking you could make the setters private and have __set() access them and get return values from them. That way you could use $thing->name = 1234; while still having individual setter functionality.Buttle Butkus
Yeah, though I would leave the setters public if I did that. (Then again, I'm heavily biased against __set and __get. The 'magic' they provide also makes knowing the structure of the class very difficult from the outside without a lot of explicit documentation.)Corbin

2 Answers

1
votes

That's up to you. If you insist on using magic methods for setting an object's properties then you need to decide if you want the class to also be responsible for data validation or whether that should be another object's (or set of objects') job.

0
votes

You could build an array to map each property with a validator, then on the __set method, execute the assigned validator for that property and value.