note 70886 added to ref.overload

From: Date: Thu, 02 Nov 2006 17:07:14 +0000
Subject: note 70886 added to ref.overload
Groups: php.notes 
Request: Send a blank email to php-notes+get-119319@lists.php.net to get a copy of this message
Simple way to restrict class property access (read and/or write) and range checking on setting, custom get also. <?php final class test { protected $x; protected $y; protected $z; private $publicRead = Array( 'x'=>"", 'y'=>"", 'z'=>"getZ" ); private $publicWrite = Array( 'x'=>"setX", 'y'=>"setY" ); final public function test(){ $this->x = 0; $this->y = 0; $this->z = 100; return $this; } final public function setX($val){ //allow only 1 - 10 if ($val > 0 && $val < 11){ $this->x = $val; } else { echo "Cannot set X to $val, valid range is 1-10\n<br />"; } } final public function setY($val){ //allow only 11 - 20 if ($val > 10 && $val < 21){ $this->y = $val; } else { echo "Cannot set Y to $val, valid range is 11-20\n<br />"; } } final public function getZ(){ return ($this->z*2)." (x2) "; } final private function __get($nm) { if (array_key_exists($nm, $this->publicRead)){ $method = $this->publicRead[$nm]; if ($method != ""){//if we have a custom get method use it return $this->$method(); } else { //else return the value directly return $this->$nm; } } else { echo "Cannot get protected property ".get_class($this)."::$nm\n<br />"; return null; } } final private function __set($nm, $val) { if (array_key_exists($nm, $this->publicWrite)){ $method = $this->publicWrite[$nm]; $this->$method($val); } else { echo "Cannot set protected property ".get_class($this)."::$nm\n<br />"; } } } $t = new test; $t->x = 1; $t->y = 113; $t->z = 1001; echo "<br /><br />"; echo "X:".$t->x."<br />"; echo "Y:".$t->y."<br />"; echo "Z:".$t->z."<br />"; ?> ---- Server IP: 85.116.0.130 Probable Submitter: 86.131.196.110 ---- Manual Page -- http://www.php.net/manual/en/ref.overload.php Edit -- https://master.php.net/note/edit/70886 Del: integrated -- https://master.php.net/note/delete/70886/integrated Del: useless -- https://master.php.net/note/delete/70886/useless Del: bad code -- https://master.php.net/note/delete/70886/bad+code Del: spam -- https://master.php.net/note/delete/70886/spam Del: non-english -- https://master.php.net/note/delete/70886/non-english Del: in docs -- https://master.php.net/note/delete/70886/in+docs Del: other reasons-- https://master.php.net/note/delete/70886 Reject -- https://master.php.net/note/reject/70886 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#119319) next »