yii2使用行为behavior

1 添加behavior文件 /basic/components/behavior/MyBehavior.php

<?php
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;
    }
}

2 controller添加behaviors /basic/controller/TestController.php

    public function behaviors()
    {
        return [
            'MyBehavior'=>[
                'class'=>MyBehavior::className(),
                'name'=>'jerry',
                'age'=>20
            ]
        ];
    }

3 添加测试代码 /basic/controller/TestController.php

 public function actionIndex()
    {
        var_dump($this->name);
        var_dump($this->age);
    }

4 访问http://www.basic.com/test/index

posted @ 2021-06-22 23:36  胡勇健  阅读(49)  评论(0编辑  收藏  举报