<?php class OtherShop { function thing() { print "thing\n"; } function andAnotherthing() { print "another thing\n"; } } class Delegator { private $thirdpartyShop; function __construct() { $this->thirdpartyShop = new OtherShop(); } function __call($method, $args) { if (method_exists($this->thirdpartyShop, $method)) { return $this->thirdpartyShop->{$method}(); } } } $d = new Delegator(); $d->thing();
<?php class Delegator { function __construct() { $this->delegate = NULL; } function operation() { if (method_exists($this->delegate, "thing")) { return $this->delegate->thing(); } return 'default implementation'; } } class Delegate { function thing() { return 'Delegate Implementation'; } } $a = new Delegator(); print "{$a->operation()}\n"; $a->delegate = 'A delegate may be any object'; print "{$a->operation()}\n"; $a->delegate = new Delegate(); print "{$a->operation()}\n";
<?php class Delegator extends Object { } abstract class DelegatorMethods { function delegate($delegated_methods) { $delegated_methods = func_get_args(); $receiver = array_pop($delegated_methods); if (empty($delegated_methods)) { trigger_error('The last argument to delegate() must be an object or a string representing a class or method', E_USER_ERROR); } else { $class = get_called_class(); $methods =& call_class_method($class, 'methods'); foreach ($delegated_methods as $delegated_method) { if (!isset($methods[$delegated_method])) { $methods[$delegated_method] = array(); } array_unshift($methods[$delegated_method], array($receiver, $delegated_method)); } } } } Delegator::extend('DelegatorMethods');
<?php class OtherShop { function thing() { print "thing\n"; } function andAnotherthing($a, $b) { print "another thing ({$a}, {$b})\n"; } } class Delegator { private $thirdpartyShop; function __construct() { $this->thirdpartyShop = new OtherShop(); } function __call($method, $args) { if (method_exists($this->thirdpartyShop, $method)) { return call_user_func_array(array($this->thirdpartyShop, $method), $args); } } } $d = new Delegator(); $d->andAnotherThing("a", "b");