Say hypothetically I have a class...
class Main { $prop1 = 2; $prop2 = 23; ... $prop42 = "what"; function __construct($arg_array) { foreach ($arg_array as $key => $val) { $this->$key = $val; } } }
Say I create and object...
$attributes = array("prop1"=>1, "prop2"=>35235, "prop3"=>"test"); $o = new Main($attributes);
Providing for default property values if not supplied by the user is obvious. But what if I want to enforce arbitrary limits on user supplied values for object properties? What if I want to enforce $prop1
to be of int
, be no less than 1, and be no greater than 5. And, $prop42
to be of type string
, no less than 'A', and no greater than 'Z'? For this purpose, what would be the cleanest way, keeping the script as short and sweet as possible, using any possible language feature or trick?
I'm stuck in __construct()
checking supplied values against a rule array built like so...
$allowable = array( "prop1" => array( 'type' => 'int', 'allowable_values' => array( 'min' => 1, 'max' => 5 ) ), "prop2" => array( 'type' => 'int', 'allowable_values' => array( 1, 235, 37, 392, 13, 409, 3216 ) ), ... "prop42" => array( 'type' => 'string', 'allowable_values' => array( 'min' => 'A', 'max' => 'Z' ) ) );
As you can see by prop2
, my validation function is starting to get pretty messy with so many 'if-then-iterate-again' blocks as I have to account for not only ranges but a list of permitted values. With the validation code and this rule array, my script is getting rather bulky.
The question is, how can I structure my class or class properties or the validation code or any other aspect of my script to be as short and concise as possible to allow property range and value enforcement? Is there a language feature or trick to handle this more elegantly? Have I reached a brick wall, the limit of this language? Are there any examples from other languages that can easily implement this which can provide some clue?