yii2:行为
行为是 yiiaseBehavior 或其子类的实例。
就是:将一个类的属性和方法,赋给另一个类使用。
例如:
behavior
namespace appcomponentsehavior; use yiiaseBehavior; 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 appmodulesdemocontrollers; use Yii; use appmodelsDCountry; use yiiwebController; use appcomponentsehaviorMyBehavior; //use appcompon /** * 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]); } }