note 62195 deleted from language.oop5.overloading by googleguy

From: Date: Tue, 22 Oct 2013 14:55:35 +0000
Subject: note 62195 deleted from language.oop5.overloading by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-197243@lists.php.net to get a copy of this message
Note Submitter: Eric Lafkoff ---- If you're wondering how to create read-only properties for your class, the __get() and __set() functions are what you're looking for. You just have to create the framework and code to implement this functionality. Here's a quick example I've written. This code doesn't take advantage of the "type" attribute in the properties array, but is there for ideas. <?php class Test { private $p_arrPublicProperties = array( "id" => array("value" => 4, "type" => "int", "readonly" => true), "datetime" => array("value" => "Tue 02/21/2006 20:49:23", "type" => "string", "readonly" => true), "data" => array("value" => "foo", "type" => "string", "readonly" => false) ); private function __get($strProperty) { //Get a property: if (isset($this->p_arrPublicProperties[$strProperty])) { return $this->p_arrPublicProperties[$strProperty]["value"]; } else { throw new Exception("Property not defined"); return false; } } private function __set($strProperty, $varValue) { //Set a property to a value: if (isset($this->p_arrPublicProperties[$strProperty])) { //Check if property is read-only: if ($this->p_arrPublicProperties[$strProperty]["readonly"]) { throw new Exception("Property is read-only"); return false; } else { $this->p_arrPublicProperties[$strProperty]["value"] = $varValue; return true; } } else { throw new Exception("Property not defined"); return false; } } private function __isset($strProperty) { //Determine if property is set: return isset($this->p_arrPublicProperties[$strProperty]); } private function __unset($strProperty) { //Unset (remove) a property: unset($this->p_arrPublicProperties[$strProperty]); } } $objTest = new Test(); print $objTest->data . "\n"; $objTest->data = "bar"; //Works. print $objTest->data; $objTest->id = 5; //Error: Property is read-only. ?>

« previous php.notes (#197243) next »