use __call() to create a delegation model

__call()
can be used for a variety of purposes. The following example
shows how to create a delegation model, in which an instance of the class
HelloWorldDelegator
delegates all method calls to an instance of the
HelloWorld
class:
class HelloWorld {
function display($count)
{
for ($i = 0; $i < $count; $i++) {
print "Hello, World\n";
}
return $count;
}
}
class HelloWorldDelegator {
function __construct()
{
$this->obj = new HelloWorld();
}
function __call($method, $args)
{
return call_user_func_array(array($this->obj , $method),

$args);
}
private $obj;
}
$obj = new HelloWorldDelegator();
print $obj->display(3);
This script’s output is
Hello, World
Hello, World
Hello, World
3
The
call_user_func_array()
function allows
__call()
to relay the function
call with its arguments to
HelloWorld::display()
which prints out
"Hello,
World\n"
three times. It then returns
$count
(in this case,
3
) which is then
printed out. Not only can you relay the method call to a different object (or
handle it in whatever way you want), but you can also return a value from
__call()
, just like a regular method.
 

你可能感兴趣的:(PHP,职场,休闲,delegation,__call)