note 48440 deleted from language.oop5.overloading by cmb

From: Date: Sun, 18 Dec 2016 09:55:47 +0000
Subject: note 48440 deleted from language.oop5.overloading by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-208647@lists.php.net to get a copy of this message
Note Submitter: mileskeaton at gmail dot com ---- <?php ## THE PROBLEM: Class with lots of attributes. ## You want to use $o->getVarName() or $o->get_varname() style getters ## Some attributes have custom get functions, but the rest don't ## THE SOLUTION: __call class Person { ## this top stuff is just an example. could be anything. private $name; private $age; private $weight; function __construct($name, $age, $weight) { $this->name = $name; $this->age = $age; $this->weight = $weight; } ## PORTABLE: use this __call function in any class function __call($val, $x) { # see if they're calling a getter method - and try to guess the variable requested if(substr($val, 0, 4) == 'get_') { $varname = substr($val, 4); } elseif(substr($val, 0, 3) == 'get') { $varname = substr($val, 3); } else { die("method $val does not exist\n"); } # now see if that variable exists: foreach($this as $class_var=>$class_var_value) { if(strtolower($class_var) == strtolower($varname)) { return $class_var_value; } } return false; } # IMPORTANT: you can keep some things private - or treat # some vars differently by giving them their own getter method # See how this function lies about Person's weight. function getWeight() { return intval($this->weight * .8); } } $a = new Person('Miles', 35, 200); # these all work (case-insensitive): print $a->get_name() . "\n"; print $a->getName() . "\n"; print $a->get_Name() . "\n"; print $a->getname() . "\n"; print $a->get_age() . "\n"; print $a->getAge() . "\n"; print $a->getage() . "\n"; print $a->get_Age() . "\n"; # defined functions still override the __call print $a->getWeight() . "\n"; # trying to get something that doesn't exist returns false print $a->getNothing(); # this still gets error: print $a->hotdog(); ?>

« previous php.notes (#208647) next »