<html>
<body>
<?php
//代理对象,一台打印机
class Printer
{
public function printSth($args)
{
echo 'I can print'.$args[0].'<br>';
}
// some more function below
// ...
}
//这是一个文印处理店,只文印,卖纸,不照相
class TextShop
{
private $printer;
public function __construct(Printer $printer)
{
$this->printer = $printer;
}
//卖纸
public function sellPaper()
{
echo 'give you some paper <br>';
}
//将代理对象有的功能交给代理对象处理
public function __call($method, $args)
{
if(method_exists($this->printer, $method))
{
$this->printer->$method($args);
}
}
}
//这是一个照相店,只文印,拍照,不卖纸
class PhotoShop
{
private $printer;
public function __construct(Printer $printer)
{
$this->printer = $printer;
}
//照相
public function takePhotos()
{
echo 'take photos for you <br>';
}
//将代理对象有的功能交给代理对象处理
//当本对象没有$textShop->printSth("_t")要的printSht方法时,__call函数被调用
//$method是$textShop->printSth("_t")中将要使用的方法printSth
//$args是$textShop->printSth("_t")里头的参数_t
public function __call($method, $args)
{
if(method_exists($this->printer, $method))//检查$this->printer中有没有$method方法
{
$this->printer->$method($args);//这里的printer是代理了new Printer的功能
}
}
}
$printer = new Printer();
$textShop = new TextShop($printer);
$photoShop = new PhotoShop($printer);
$textShop->printSth("_t");
$photoShop->printSth("_p");
?>
</body>
</html>
各个店都要打印,但没有打印功能,就代理了一台公共的外部打印机
当有需要打印时,__call函数就其作用了