[ create a new paste ] login | about

Project: fedecarg
Link: http://fedecarg.codepad.org/0eDBDVYY    [ raw code | output | fork ]

PHP, pasted on Mar 19:
<?php
class ClassOne 
{
	public function callClassOne() {
		print "In Class One\n";
	}
}

class ClassTwo 
{
	public function callClassTwo() {
		print "In Class Two\n";
	}
}

class ClassOneDelegator 
{
	private $targets;

	function __construct() {
		$this->target[] = new ClassOne();
	}

	function addObject($obj) {
		$this->target[] = $obj;
	}

	function __call($name, $args) {
		foreach ($this->target as $obj) {
			$r = new ReflectionClass($obj); 

			if ($method = $r->getMethod($name)) {
				if ($method->isPublic() && !$method->isAbstract()) {
					return $method->invoke($obj, $args);
				}
			}
		}
	}
}

$obj = new ClassOneDelegator();
$obj->addObject(new ClassTwo());
$obj->callClassOne();
$obj->callClassTwo();


Output:
1
2
3
4
5
6
7
8
9
In Class One

Fatal error: Uncaught exception 'ReflectionException' with message 'Method callClassTwo does not exist' in /t.php:32
Stack trace:
#0 /t.php(32): ReflectionClass->getMethod('callClassTwo')
#1 [internal function]: ClassOneDelegator->__call('callClassTwo', Array)
#2 /t.php(44): ClassOneDelegator->callClassTwo()
#3 {main}
  thrown in /t.php on line 32


Create a new paste based on this one


Comments: