Behaviors are instances of yii\base\Behavior, or of a child class. Behaviors, also known as mixins, allow you to enhance the functionality of an existing component class without needing to change the class's inheritance. Attaching a behavior to a component "injects" the behavior's methods and properties into the component, making those methods and properties accessible as if they were defined in the component class itself.
Moreover, a behavior can respond to the events triggered by the component, which allows behaviors to also customize the normal code execution of the component.



// 参考了下面链接1,但修改

// Step 1: 定义一个将绑定行为的类
class MyClass extends yii\base\Component
  // 空的

// Step 2: 定义一个行为类,他将绑定到MyClass上
class MyBehavior extends yii\base\Behavior
  // 行为的一个属性
  public $property1 = 'This is a public property in MyBehavior.';
  private $_property2 = 'This is a private property in MyBehavior.';

   public function getProperty2()
        return $this->_property2;

    public function setProperty2($value)
        $this->_property2 = $value;

  // 行为的一个方法
  public function foo()
    return 'Method Foo in MyBehavior is called.';

$myClass = new MyClass();
$myBehavior = new MyBehavior();

// Step 3: 将行为绑定到类上
$myClass->attachBehavior('myBehavior', $myBehavior);

// Step 4: 访问行为中的属性和方法,就和访问类自身的属性和方法一样
echo $myClass->property1; 
echo $myClass->getProperty2;
echo $myClass->foo();


yii\base\Model      »   yii\base\Component      » yii\base\BaseObject
yii\base\Controller »   yii\base\Component      » yii\base\BaseObject
                        yii\base\Behavior       » yii\base\BaseObject


标签: Bahavior, Component