2016年3月13日 星期日

PHP decorator + __call

``` class Weapon { public function attack() { return 10; } } abstract class Decorator { protected $weapon; public function __construct($weapon) { $this->weapon = $weapon; } abstract public function attack(); public function __call($method, $parameters) { return call_user_func_array([$this->weapon, $method], $parameters); } } class ToxicDecorator extends Decorator { public function attack() { return $this->weapon->attack() + 15; } public function toxic() { echo 'toxic'; } } class LightingDecorator extends Decorator { public function attack() { return $this->weapon->attack() + 5; } public function lighting() { echo 'lighting'; } } $weapon = new Weapon(); $weapon = new ToxicDecorator($weapon); $weapon = new LightingDecorator($weapon); echo $weapon->attack(); echo $weapon->toxic(); echo $weapon->lighting(); // output // 30 // toxic // lighting ```

沒有留言:

張貼留言