note 46125 added to language.oop5.overloading

From: Date: Thu, 30 Sep 2004 01:14:41 +0000
Subject: note 46125 added to language.oop5.overloading
Groups: php.notes 
Request: Send a blank email to php-notes+get-77602@lists.php.net to get a copy of this message
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 />'; ---- Manual Page -- http://www.php.net/manual/en/language.oop5.overloading.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+46125 Delete -- http://master.php.net/manage/user-notes.php?action=delete+46125&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+46125&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#77602) next »