【问题标题】:Unable to access protected variable within class when declaring variable声明变量时无法访问类中的受保护变量
【发布时间】:2019-11-21 10:21:57
【问题描述】:

我是 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();```

【问题讨论】:

  • 您是否检查过您的错误日志等。
  • 我在 php_error.log 文件中没有发现任何错误。当我拨打电话时它不会抛出错误,它不会更新数据库。我还确保使用 dd() 将描述添加到 setDescription 函数中,并且一切都在那里
  • 你是如何使用它的?它应该可以工作。
  • 我刚刚修改了帖子以包含实现
  • 这可能是由于对象继承,虽然我可能是错的。如果你想让描述成为一个受保护的属性,那么使用protected $protectedProperties = [ 'description' ];stackoverflow.com/questions/46376646/…

标签: php laravel class eloquent lumen


【解决方案1】:

Eloquent 不知道该受保护的属性。所有 Eloquent 模型属性都通过 attributes 属性进行维护。如果您希望以这种方式完成设置值,请使用 setDescription 方法中的 attributes 属性:

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

更多信息请参见mutators

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-23
    • 1970-01-01
    • 2014-04-21
    • 2014-05-14
    • 2017-01-12
    • 2023-01-13
    • 2019-10-27
    相关资源
    最近更新 更多