php 向 Laravel 模型添加 Setter 和 Getter
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40337400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding Setters and Getters to Laravel Model
提问by Gazzer
If I want an Eloquent Model class to have setters and getters for the sake of implementing an interface does the following approach make sense or is there a 'laravel' approach to the problem
如果我希望 Eloquent Model 类为了实现接口而具有 setter 和 getter,那么以下方法是否有意义,或者是否有解决问题的“laravel”方法
class MyClass extends Model implements someContract
{
public function setFoo($value) {
parent::__set('foo', $value);
return $this;
}
public function getFoo() {
return parent::__get('foo');
}
}
回答by Alexey Mezenin
You are probably looking for accessors(getters) and mutators(setters).
您可能正在寻找访问器(getter)和修改器(setter)。
Example of an accessor (getter) in Laravel:
Laravel 中的访问器(getter)示例:
public function getFirstNameAttribute($value)
{
return ucfirst($value);
}
Example of a mutator (setter) in Laravel:
Laravel 中的 mutator(setter)示例:
public function setFirstNameAttribute($value)
{
$this->attributes['first_name'] = strtolower($value);
}