声明变量时无法访问类内的受保护变量

时间:2019-07-11 16:25:51

标签: php laravel class eloquent lumen

我是laravel / php的新手,希望有人能够为我回答一个问题。然后,当我使用asset-> setDescription时,一切正常,但是一旦取消注释“ protected $ description”,setDescription方法便停止工作。有人知道为什么会这样吗?

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Asset extends Model
{
    protected $fillable = [
        'type', 'title','origin',
    ];
    // protected $description;
    public function __construct($type, $title, $origin)
    {
        $this->setType($type);
        $this->setTitle($title);
        $this->setOrigin($origin);
    }
    // Setters
    public function setType($type){
        $this->type = $type;
    }
    public function setTitle($title)
    {
        $this->title = $title;
    }
    public function setOrigin($origin)
    {
        $this->origin = $origin;
    }
    public function setDescription($description)
    {
        $this->description = $description;
    }
}

$type = $request->input('type');
$title = $request->input('title');
$origin = $request->input('origin');

// Create new asset
$asset = new Asset($type, $title, $origin);
$asset->setDescription('test');

$asset->save();```

1 个答案:

答案 0 :(得分:0)

口才不知道该受保护的财产。所有Eloquent Model属性都是通过attribute属性维护的。如果您希望以这种方式完成设置值,请在setDescription方法中使用attributes属性:

public function setDescription($description)
{
    $this->attributes['description'] = $description;
}

有关更多信息,请参见mutators