note 103175 added to language.oop5.overloading

From: Date: Wed, 30 Mar 2011 01:46:45 +0000
Subject: note 103175 added to language.oop5.overloading
Groups: php.notes 
Request: Send a blank email to php-notes+get-178333@lists.php.net to get a copy of this message
A controlled way to chain the results of a method call onto a new property. I thought it was impossible to do cleanly but I finally found a decent way of handling it. <?php class main { public function newMember($value) { return new sub($this, $value); } } class sub { protected $parent; protected $value; public function __construct($parent, $value) { $this->parent = $parent; $this->value = $value; } public function __get($name) { $this->parent->$name = $this->value; return $this; } public function __call($name, $args) { // Invoke parent class. return call_user_func_array(array($this->parent, $name), $args); } } $object = new main(); $object->newMember('value for foo')->foo->newMember('value for bar')->bar; print var_dump($object->foo); print var_dump($object->bar); // prints out "value for foo" and "value for bar". ?> Without the secondary 'sub' class, the chaining can be unpredictable since it doesn't carry over any state information. This way you can encapsulate the results into the supporting class and let it do the work. ---- Server IP: 69.147.83.197 Probable Submitter: 69.248.124.214 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.overloading.php Edit -- https://master.php.net/note/edit/103175 Del: integrated -- https://master.php.net/note/delete/103175/integrated Del: useless -- https://master.php.net/note/delete/103175/useless Del: bad code -- https://master.php.net/note/delete/103175/bad+code Del: spam -- https://master.php.net/note/delete/103175/spam Del: non-english -- https://master.php.net/note/delete/103175/non-english Del: in docs -- https://master.php.net/note/delete/103175/in+docs Del: other reasons-- https://master.php.net/note/delete/103175 Reject -- https://master.php.net/note/reject/103175 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#178333) next »