ErrorException: Indirect modification of overloaded property App\Answer::$attribute has no effect

我怕爱的太早我们不能终老 提交于 2021-02-07 10:55:02

问题


I get this exception when Answer model I am trying to change value of 'ans' attribute from my answers table database.

public function setAnsAttribute($ans){

}

ErrorException: Indirect modification of overloaded property
App\Answer::$attribute has no effect


回答1:


The setAnsAtribute method has no code? If you have code, please add more code to see what is happening. Thank you.

If you do not have a code, I will indicate it below.

I refer you to the Laravel Mutators page so you can see the example and attach an example code with what you are trying to do.

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;
}



回答2:


I have never encountered this error so I did a little research and created the following to illustrate the issue:

The class:

class SomeMagicMethodImplementer
{
    private $properties = [];

    public function __get($k)
    {
        return $this->properties[$k] ?? null;
    }

    public function __set($k, $v)
    {
        $this->properties[$k] = $v;
    }
}  

The usage:

$impl = new SomeMagicMethodImplementer();
$impl->bar = 'bar';
print_r($impl->bar); // prints bar
$impl->foo[] = 'foo';

The cause of the error:

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

Indirect modification of overloaded property

Using the example code above, this error essentially states that any property created via the magic setter can only be modified through the private instance variable $properties.

In the context of Laravel and a model, the property can only be modified through the protected instance variable $attributes.

Laravel Example:

public function setAnsAttribute($value)
{
    // output will be an array
    $this->attributes['ans'][] = $value;
}


来源:https://stackoverflow.com/questions/57100550/errorexception-indirect-modification-of-overloaded-property-app-answerattrib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!