note 91687 deleted from language.oop5 by danbrown
| From: | danbrown@php.net | Date: | Tue, 23 Jun 2009 13:27:05 +0000 |
| Subject: | note 91687 deleted from language.oop5 by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-157263@lists.php.net to get a copy of this message | ||
Note Submitter: edgar at goodforall dot eu
----
@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
*/
?>