yii2:行为
行为是 yii\base\Behavior 或其子类的实例。
就是:将一个类的属性和方法,赋给另一个类使用。
例如:
behavior
namespace app\components\behavior;use yii\base\Behavior;class MyBehavior extends Behavior{ public $name; public $age; public function setName($name) { $this->name = $name; } public function getName() { return $this->name; } public function setAge($age) { $this->age = age; } public function getAge() { return $this->age; }}
然后controller中使用:
namespace app\modules\demo\controllers;use Yii;use app\models\DCountry;use yii\web\Controller;use app\components\behavior\MyBehavior;//use app\compon/** * Default controller for the `demo` module */class DefaultController extends Controller{ public $url; public function behaviors() { return [ // 匿名行为,只有行为类名 'MyBehavior'=>[ 'class'=>MyBehavior::className(), 'name'=>'jerry', 'age'=>20 ] ]; } /** * Renders the index view for the module * @return string */ public function actionIndex() { return $this->render('index', ['age'=>$this->age, 'name'=>$this->name]); }}