note 106382 added to language.oop5.overloading

From: Date: Wed, 02 Nov 2011 20:57:34 +0000
Subject: note 106382 added to language.oop5.overloading
Groups: php.notes 
Request: Send a blank email to php-notes+get-184278@lists.php.net to get a copy of this message
If a class is being extended by another class, its __get and __set methods (and others) can also be overloaded themselves: <?php class A { public function __get($value){ switch($value){ case "a1": return 1; break; case "a2": return 2; break; default: // error handler goes here return "number out of range"; // or NULL or anything else } } // end of method __get } // end of class A class B extends A { public function __get($value){ switch($value){ case "a1": return 11; break; // we overload value of 1 case "b3": return 3; break; // we add these new properties case "b4": return 4; break; default: // check ancestor's properties return parent::__get($value); } } // end of method __get } //end of class B $a=new A(); $b=new B(); echo $a->a1; // produces 1 echo $a->a2; // produces 2 echo $a->b3; // produces number out of range echo $b->a1; // produces 11 echo $b->a2; // produces 2 echo $b->b3; // produces 3 echo $b->b4; // produces 4 echo $b->b5; // produces number out of range ?> If class B's default switch option is reached, the class A's getter is called. So the extending class B overloads property "a1", adds its own properties "b3" and "b4", and inherits property "a2". This solution can't, however, overload class A's error handler (the line with "number out of range"). Should it be needed, consider the following error handler of the class B: <?php default: // error handler goes here $p=parent::__get($value); if(!is_numeric($p)){ return "no value"; // overload class A's error message } else{ return $p; // return class A's base properties } ?> So we have new "error handler" <?php echo $b->b5; // produces no value ?> ---- Server IP: 69.147.83.197 Probable Submitter: 89.76.144.156 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.overloading.php Edit -- https://master.php.net/note/edit/106382 Del: integrated -- https://master.php.net/note/delete/106382/integrated Del: useless -- https://master.php.net/note/delete/106382/useless Del: bad code -- https://master.php.net/note/delete/106382/bad+code Del: spam -- https://master.php.net/note/delete/106382/spam Del: non-english -- https://master.php.net/note/delete/106382/non-english Del: in docs -- https://master.php.net/note/delete/106382/in+docs Del: other reasons-- https://master.php.net/note/delete/106382 Reject -- https://master.php.net/note/reject/106382 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#184278) next »