views:

31

answers:

2

Hi,

I have a class that uses the __set magic method. One of the properties for the class can only be set with a certain range of string values, the best example I can think of is the mysql datatype ENUM('value_one','value_two','value_three').

Would I place conditional statements within the __set method to distinguish between which property is being set and whether the value is valid for that property?

Are large switch statements inside a __set method considered sloppy practice, is their a better way of producing the desired results?

Thanks, Ben

A: 

The __set function could check for the existance of a method named similar to presetVariableName, which is called and passed the new value as a parameter.

That function could then perform the validation logic, and return true or false as to whether it's valid or not.

Matt
Or you could name the method `setVariableName` and use it as a setter. The magic method would therefore only be used as a "shortcut". Plus that lets you only implement the specific setter for those variables that need validation (saving the code you need to write)...
ircmaxell
I'm personally not a fan of having two ways to set a property, i.e., `$obj->color = 'blue'` and `$obj->setColor('blue')`. I prefer the interface to have one way or the other. However, that's just me and many people do it both ways.
webbiedave
Thank you for all your comments gave me much better understanding of how best to perform the required logic!
Globalz
A: 

Would I place conditional statements within the __set method to distinguish between which property is being set and whether the value is valid for that property?

Yes to the first part, no to the second.

Are large switch statements inside a __set method considered sloppy practice, is their a better way of producing the desired results?

Your __set method should determine which variable is trying to be set and then pass off the rest of the functionality to a private setter setParticularVar. setParticularVar will then contain the logic specific to validating that variable and can throw an exception if an invalid value is passed.

Alternatively, you could make the private setter public instead, allowing two ways to set the variable but this is not as desirable as two ways to set a value is not as clean a design.

webbiedave