简体   繁体   中英

How to make dynamic attributes in Yii2 like in Laravel?

In Laravel I can write

class MyModel extends Model {
    public function getTextAttribute($value) {
        return strtoupper($value);
    }
}

And then

$model = MyModel::find(1);
$model->text = 'test';
echo $model->text; // returns 'TEXT'

Can I do similar in Yii2?

Add a public var in your MyModel and you can redifine the text getter this way

class MyModel extends Model {

    public $text;

    public function getText() {
        return strtoupper($this->text);
    }
}

.

 $model= MyModel::findOne(1);
 $model->text =  'test';
 echo $model->text; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM