PHP behavior 机制简单实现

<?php
class Base{
    private $_m = array();
    public function attachBehavior($behaviorObj){
            $behaviorObj->attach($this);
            $this->_m[] = $behaviorObj;
    }

    public function __call($method,$param){
       foreach($this->_m as $obj){
            if(method_exists($obj,$method)){
                 call_user_func(array($obj,$method),$param);
            }
       }
    }
}

class Behavior{
    protected $scope;
    public function attach($scope){
        $this->scope = $scope;
    }
}

class BehaviorTest extends Behavior{

   public function prints($param){
       print_r($this->scope);
   }
}

class TestObj extends Base{
   public function __construct(){
       $this->name = 'test';
       $this->age = 20;
   }
}

$behaviorTestIns = new BehaviorTest();
$baseIns = new TestObj();
$baseIns->attachBehavior($behaviorTestIns);
$baseIns->prints();


?>

 

posted @ 2013-08-06 13:14  ﹏Sakura  阅读(805)  评论(0编辑  收藏  举报