You can attach a behavior to a [[yii\base\Component|component]] either statically or dynamically. The former
You can attach a behavior to a [[yii\base\Component|component]] either statically or dynamically. The former is more common in practice.
is more commonly used in practice.
To attach a behavior statically, override the [[yii\base\Component::behaviors()|behaviors()]] method of the component
To attach a behavior statically, override the [[yii\base\Component::behaviors()|behaviors()]] method of the component
class that it is being attached. For example,
class to which the behavior is being attached. The [[yii\base\Component::behaviors()|behaviors()]] method should return a list of behavior [configurations](concept-configurations.md).
Each behavior configuration can be either a behavior class name or a configuration array:
```php
```php
namespaceapp\models;
namespaceapp\models;
...
@@ -141,16 +141,11 @@ class User extends ActiveRecord
...
@@ -141,16 +141,11 @@ class User extends ActiveRecord
}
}
```
```
The [[yii\base\Component::behaviors()|behaviors()]] method should return a list of behavior [configurations](concept-configurations.md).
You may associate a name with a behavior by specifying the array key corresponding to the behavior configuration. In this case, the behavior is called a *named behavior*. In the above example, there are two named behaviors:
Each behavior configuration can be either a behavior class name or a configuration array.
You may associate a name with a behavior by specifying the array key corresponding to the behavior configuration.
In this case, the behavior is called a *named behavior*. In the above example, there are two named behaviors:
`myBehavior2` and `myBehavior4`. If a behavior is not associated with a name, it is called an *anonymous behavior*.
`myBehavior2` and `myBehavior4`. If a behavior is not associated with a name, it is called an *anonymous behavior*.
To attach a behavior dynamically, call the [[yii\base\Component::attachBehavior()]] method of the component
To attach a behavior dynamically, call the [[yii\base\Component::attachBehavior()]] method of the component to which the behavior is being attached: