是什么导致此 Codeigniter 3 应用程序中的错误 "Can't use method return value in write context"?

What causes the error "Can't use method return value in write context" in this Codeigniter 3 application?

我正在使用 Codeigniter 3 社交网络 应用程序,Ion-Auth and Bootstrap 4. You can see the Github repo HERE.

编辑用户个人资料时,我检查编辑表单中是否有新的用户照片(头像)。如果是,我使用它,如果不是我使用(保留)userstable中已经存在的那个(文件路径是application/controllers/Auth.php):

$new_file = $this->upload->data('file_name');
$this->file_name = (isset($new_file) && !empty($new_file)) ? $new_file : $user->avatar;

以上代码工作正常。

但是,我需要在会话中更新用户的照片,为此我在下面添加了 $this->file_name = (isset($new_file) && !empty($new_file)) ? $new_file : $user->avatar:

if (isset($new_file) && !empty($new_file)) {
    $this->session->userdata('user_avatar') = $new_file;
}

上述 if 语句导致错误“无法在写入上下文中使用方法 return 值”。

我做错了什么?

您通常会在调用执行写入的方法的 if 语句中遇到该错误。

有关 isset 和 empty 的使用,请参阅 Why check both isset() and !empty()。您不需要同时使用两者。

if (isset($new_file) && !empty($new_file)) {
    $this->session->userdata('user_avatar') = $new_file;
}

此处您应该使用 $this->session->set_userdata('user_avatar',$new_file)(根据用户指南)。

于是就变成了

if (!empty($new_file)) {
    $this->session->set_userdata('user_avatar',$new_file);
}

您甚至不需要考虑使用 isset(),因为您在上面的代码中定义了 $new_file,因此它将始终为“设置”,即 isset($new_file) 将始终为真。

但是如果$new_file为空,你打算怎么办?这是你需要考虑的问题。