note 91687 added to language.oop5

From: Date: Tue, 23 Jun 2009 13:09:35 +0000
Subject: note 91687 added to language.oop5
Groups: php.notes 
Request: Send a blank email to php-notes+get-157262@lists.php.net to get a copy of this message
@midir 02-Mar-2009 03:40 Another solution is to use (some kind of?) a proxy object. In this example ProxyObject encapsulates an object, which type is determined runtime from the arguments passed to its constructor. With __call it pass the method calls to the encapsulated object. I also show how you can enforce an interface on these objects. It is all pretty basic. But hopefully it will help someone. <?php interface ITypeObject { public function getData(); public function whoAmI(); } class IntObject implements ITypeObject { protected $int; public function __construct($args){ $this->int = $args; } public function getData(){ return $this->int; } public function whoAmI(){ return __CLASS__; } } class GenericObject implements ITypeObject { protected $generic; public function __construct($args){ $this->generic = $args; } public function getData(){ return $this->generic; } public function whoAmI(){ return __CLASS__; } } class ProxyObject { public function __construct($args){ if(is_int($args)){ $this->object = new IntObject($args); } else { $this->object = new GenericObject($args); } if(! $this->object instanceof ITypeObject){ throw new Exception(get_class($this->object) . ' should implement ITypeObject'); } } public function __call($method, $args){ if(is_callable(array($this->object, $method))){ return $this->object->$method($args); } else { throw new Exception('Method: ' .$method .' doesn\'t exist.'); } } } $tp = new ProxyObject(5); print $tp->getData() ."\n"; print $tp->whoAmI() . "\n"; /** * Outputs: 5 * IntObject */ $tp = new ProxyObject("5"); print $tp->getData() ."\n"; print $tp->whoAmI() . "\n"; /** * Outputs: 5 * GenericObject */ ?> ---- Server IP: 91.199.167.18 Probable Submitter: 92.65.202.83 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.php Edit -- https://master.php.net/note/edit/91687 Del: integrated -- https://master.php.net/note/delete/91687/integrated Del: useless -- https://master.php.net/note/delete/91687/useless Del: bad code -- https://master.php.net/note/delete/91687/bad+code Del: spam -- https://master.php.net/note/delete/91687/spam Del: non-english -- https://master.php.net/note/delete/91687/non-english Del: in docs -- https://master.php.net/note/delete/91687/in+docs Del: other reasons-- https://master.php.net/note/delete/91687 Reject -- https://master.php.net/note/reject/91687 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#157262) next »