note 103478 added to language.oop5.overloading

From: Date: Fri, 15 Apr 2011 10:47:32 +0000
Subject: note 103478 added to language.oop5.overloading
Groups: php.notes 
Request: Send a blank email to php-notes+get-178864@lists.php.net to get a copy of this message
Example of usage __call() to have implicit getters and setters <?php class Entity { public function __call($methodName, $args) { if (preg_match('~^(set|get)([A-Z])(.*)$~', $methodName, $matches)) { $property = strtolower($matches[2]) . $matches[3]; if (!property_exists($this, $property)) { throw new MemberAccessException('Property ' . $property . ' not exists'); } switch($matches[1]) { case 'set': $this->checkArguments($args, 1, 1, $methodName); return $this->set($property, $args[0]); case 'get': $this->checkArguments($args, 0, 0, $methodName); return $this->get($property); case 'default': throw new MemberAccessException('Method ' . $methodName . ' not exists'); } } } public function get($property) { return $this->$property; } public function set($property, $value) { $this->$property = $value; return $this; } protected function checkArguments(array $args, $min, $max, $methodName) { $argc = count($args); if ($argc < $min || $argc > $max) { throw new MemberAccessException('Method ' . $methodName . ' needs minimaly ' . $min . ' and maximaly ' . $max . ' arguments. ' . $argc . ' arguments given.'); } } } class MemberAccessException extends Exception{} class Foo extends Entity { protected $a; } $foo = new Foo(); $foo->setA('some'); // outputs some echo $foo->getA(); class Bar extends Entity { protected $a; /** * Custom setter. */ public function setA($a) { if (!preg_match('~^[0-9a-z]+$~i', $a)) { throw new MemberAccessException('A can be only alphanumerical'); } $this->a = $a; return $this; } } $bar = new Bar(); $bar->setA('abc123'); // ok $bar->setA('[]/*@...'); // throws exception ?> ---- Server IP: 147.32.160.17 Probable Submitter: 82.142.91.140 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.overloading.php Edit -- https://master.php.net/note/edit/103478 Del: integrated -- https://master.php.net/note/delete/103478/integrated Del: useless -- https://master.php.net/note/delete/103478/useless Del: bad code -- https://master.php.net/note/delete/103478/bad+code Del: spam -- https://master.php.net/note/delete/103478/spam Del: non-english -- https://master.php.net/note/delete/103478/non-english Del: in docs -- https://master.php.net/note/delete/103478/in+docs Del: other reasons-- https://master.php.net/note/delete/103478 Reject -- https://master.php.net/note/reject/103478 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#178864) next »