note 85703 added to language.oop5.constants

From: Date: Fri, 12 Sep 2008 19:12:09 +0000
Subject: note 85703 added to language.oop5.constants
Groups: php.notes 
Request: Send a blank email to php-notes+get-144375@lists.php.net to get a copy of this message
Use CONST to set UPPER and LOWER LIMITS If you have code that accepts user input or you just need to make sure input is acceptable, you can use constants to set upper and lower limits. Note: a static function that enforces your limits is highly recommended... sniff the clamp() function below for a taste. <?php class Dimension { const MIN = 0, MAX = 800; public $width, $height; public function __construct($w = 0, $h = 0){ $this->width = self::clamp($w); $this->height = self::clamp($h); } public function __toString(){ return "Dimension [width=$this->width, height=$this->height]"; } protected static function clamp($value){ if($value < self::MIN) $value = self::MIN; if($value > self::MAX) $value = self::MAX; return $value; } } echo (new Dimension()) . '<br>'; echo (new Dimension(1500, 97)) . '<br>'; echo (new Dimension(14, -20)) . '<br>'; echo (new Dimension(240, 80)) . '<br>'; ?> - - - - - - - - Dimension [width=0, height=0] - default size Dimension [width=800, height=97] - width has been clamped to MAX Dimension [width=14, height=0] - height has been clamped to MIN Dimension [width=240, height=80] - width and height unchanged - - - - - - - - Setting upper and lower limits on your classes also help your objects make sense. For example, it is not possible for the width or height of a Dimension to be negative. It is up to you to keep phoney input from corrupting your objects, and to avoid potential errors and exceptions in other parts of your code. ---- Server IP: 69.147.83.197 Probable Submitter: 67.150.123.53 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.constants.php Edit -- https://master.php.net/note/edit/85703 Del: integrated -- https://master.php.net/note/delete/85703/integrated Del: useless -- https://master.php.net/note/delete/85703/useless Del: bad code -- https://master.php.net/note/delete/85703/bad+code Del: spam -- https://master.php.net/note/delete/85703/spam Del: non-english -- https://master.php.net/note/delete/85703/non-english Del: in docs -- https://master.php.net/note/delete/85703/in+docs Del: other reasons-- https://master.php.net/note/delete/85703 Reject -- https://master.php.net/note/reject/85703 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#144375) next »