A class bound with behaviors, which looks like this:
// Step 1: 定义一个将绑定行为的类 class MyClass extends yii\base\Component { // 空的 } // Step 2: 定义一个行为类,他将绑定到MyClass上 class MyBehavior extends yii\base\Behavior { // 行为的一个属性 public $property1 = 'This is property in MyBehavior.'; // 行为的一个方法 public function method1() { return 'Method in MyBehavior is called.'; } } $myClass = new MyClass(); $myBehavior = new MyBehavior(); // Step 3: 将行为绑定到类上 $myClass->attachBehavior('myBehavior', $myBehavior); // Step 4: 访问行为中的属性和方法,就和访问类自身的属性和方法一样 echo $myClass->property1; echo $myClass->method1();
You don’t need to understand all the above codes. Although you may have guessed the meaning of these codes with your toes, here you only need to remember that the properties and methods in the behavior can be accessed by the bound class like itself. Direct access to properties and methods is OK. In the code, $myClass does not have a property1 method() member. These two are members of $myBehavior. However, after binding the behavior to the object through attachBehavior(), $myCalss seems to have mastered the magic of attracting stars and transforming energy, showing great wealth and turning other people's attributes and methods into its own.
In addition, from the above code, you also need to understand the general process of using the behavior:
To use a behavior, you must first attach it to the yiibaseComponent class or its subclasses as described previously. Once a behavior is attached to a component, you can use it directly.
After a behavior is attached to a component, you can access a behavior's public member variables or properties defined by getter and setter methods through the component:
// "prop1" 是定义在行为类的属性 echo $component->prop1; $component->prop1 = $value; 类似地也可以调用行为的公共方法: // foo() 是定义在行为类的公共方法 $component->foo();
As you can see, even though $component does not define prop1 and foo() , they are used as if they were defined by the component itself.
If two behaviors define the same property or method, and they are both attached to the same component, then the behavior attached first has priority when the property or method is accessed.
The named behavior when attaching a behavior to a component, you can use this name to access the behavior object, as shown below:
$behavior = $component->getBehavior('myBehavior');
You can also get all behaviors attached to this component:
$behaviors = $component->getBehaviors();
Remove Behavior
To remove a behavior, you can call the yiibaseComponent::detachBehavior() method using the name associated with the behavior:
$component->detachBehavior('myBehavior1');
You can also remove all behaviors:
$component->detachBehaviors();