为了账号安全,请及时绑定邮箱和手机立即绑定

ErrorException: 对重载属性 App\Answer::$attribute

ErrorException: 对重载属性 App\Answer::$attribute

PHP
阿晨1998 2021-10-15 17:31:58
当我尝试从我的答案表数据库中更改“ans”属性的值时,出现此异常。public function setAnsAttribute($ans){}ErrorException: 对重载属性App\Answer::$attribute 的间接修改无效
查看完整描述

2 回答

?
梵蒂冈之花

TA贡献1900条经验 获得超5个赞

setAnsAtribute 方法没有代码?如果您有代码,请添加更多代码以查看发生了什么。谢谢你。


如果您没有代码,我会在下面指出。


我将您推荐给 Laravel Mutators页面,以便您可以查看示例并附上示例代码以及您正在尝试执行的操作。


función pública setAnsAttribute ($value) {

    /**

     *  You can transform the value or modify other values in the table here, 

     *  according to your needs.

     */

    $this->attributes['ans'] = $value;

}


查看完整回答
反对 回复 2021-10-15
?
森栏

TA贡献1810条经验 获得超5个赞

我从来没有遇到过这个错误,所以我做了一些研究并创建了以下内容来说明这个问题:


班上:


class SomeMagicMethodImplementer

{

    private $properties = [];


    public function __get($k)

    {

        return $this->properties[$k] ?? null;

    }


    public function __set($k, $v)

    {

        $this->properties[$k] = $v;

    }

}  

用法:


$impl = new SomeMagicMethodImplementer();

$impl->bar = 'bar';

print_r($impl->bar); // prints bar

$impl->foo[] = 'foo';

错误原因:


$impl->foo[] = 'foo' // Will throw error: Indirect modification of overloaded property

间接修改重载属性


使用上面的示例代码,该错误基本上指出经由魔设定器创建的任何属性可以仅通过专用实例变量进行修改$properties。


在 Laravel 和模型的上下文中,属性只能通过 protected 实例变量进行修改$attributes。


Laravel 示例:


public function setAnsAttribute($value)

{

    // output will be an array

    $this->attributes['ans'][] = $value;

}


查看完整回答
反对 回复 2021-10-15
  • 2 回答
  • 0 关注
  • 161 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信