note 46125 deleted from language.oop5.overloading by danielc

From: Date: Thu, 03 Jul 2008 00:32:08 +0000
Subject: note 46125 deleted from language.oop5.overloading by danielc
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-141092@lists.php.net to get a copy of this message
Note Submitter: Dot_Whut? Reason: 2 ---- You can create automatic getter and setter methods for your private and protected variables by creating an AutoGetterSetter Abstract Class and having your Class inherit from it: // Automatic Getter and Setter Class // // Note: when implementing your getter and setter methods, name your // methods the same as your desired object properties, but prefix the // function names with 'get_' and 'set_' respectively. abstract class AutoGetAndSet { public function __get ($name) { try { // Check for getter method (throws an exception if none exists) if (!method_exists($this, "get_$name")) throw new Exception("$name has no Getter method."); eval("\$temp = \$this->get_$name();"); return $temp; } catch (Exception $e) { throw $e; } } public function __set ($name, $value) { try { // Check for setter method (throws an exception if none exists) if (!method_exists($this, "set_$name")) throw new Exception("$name has no Setter method (is read-only)."); eval("\$this->set_$name(\$value);"); } catch (Exception $e) { throw $e; } } } class MyClass extends AutoGetAndSet { // private and protected members private $mbr_privateVar = "privateVar"; protected $mbr_protectedVar = "protectedVar"; // 'privateVar' property, setter only (read-only property) function get_privateVar () { return $this->mbr_privateVar; } // 'protectedVar' property, both getter AND setter function get_protectedVar () { return $this->mbr_protectedVar; } function set_protectedVar ($value) { $this->mbr_protectedVar = $value; } } $myClass = new MyClass(); // Show original values, automatically uses 'get_' methods echo '$myClass->protectedVar == ' . $myClass->protectedVar . '<br />'; echo '$myClass->privateVar == ' . $myClass->privateVar . '<br />'; // Modify 'protectedVar', automatically calls set_protectedVar() $myClass->protectedVar = "Modded"; // Show modified value, automatically calls get_protectedVar() echo '$myClass->protectedVar == ' . $myClass->protectedVar . '<br />'; // Attempt to modify 'privateVar', get_privateVar() doesn't exist $myClass->privateVar = "Modded"; // throws an Exception // Code never gets here echo '$myClass->privateVar == ' . $myClass->privateVar . '<br />';

« previous php.notes (#141092) next »