yii2:行爲html
行爲是 yiibaseBehavior 或其子類的實例。web
就是:將一個類的屬性和方法,賦給另外一個類使用。yii2
轉自:http://www.cnblogs.com/acheng...app
例如:yii
behaviorthis
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中使用:url
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]); } }