Note that there are some explanatory texts on larger screens.

plurals
  1. POLeast sloppy way to enforce allowable values or ranges for class properties
    primarykey
    data
    text
    <p>Say hypothetically I have a class...</p> <pre> class Main { $prop1 = 2; $prop2 = 23; ... $prop42 = "what"; function __construct($arg_array) { foreach ($arg_array as $key => $val) { $this->$key = $val; } } } </pre> <p>Say I create and object...</p> <pre> $attributes = array("prop1"=>1, "prop2"=>35235, "prop3"=>"test"); $o = new Main($attributes); </pre> <p>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 <code>$prop1</code> to be of <code>int</code>, be no less than 1, and be no greater than 5. And, <code>$prop42</code> to be of type <code>string</code>, 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?</p> <p>I'm stuck in <code>__construct()</code> checking supplied values against a rule array built like so...</p> <pre> $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' ) ) ); </pre> <p>As you can see by <code>prop2</code>, 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.</p> <p>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?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload