是什么导致此Codeigniter 3应用程序中的错误“无法在写入上下文中使用方法返回值”?

问题描述

我正在使用Codeigniter 3, Ion-Auth 和Bootstrap 4开发社交网络应用程序。您可以看到 Github repo HERE

在编辑用户的个人资料时,我检查编辑表单中是否有新的用户照片(头像)。如果是,则使用它;如果不使用,则使用(保留)import re str = '{"purchased_at":"2020-04-21T05:55:30.000Z","product_desc":"Garnier 2019 Shampoo","onhold":{"copyright":true,"country_codes":["ABC"],"scope":"poss"},"id":"8745485"}' s = re.search('id":"(.+?)"',str) if s: print( s.group(1) ) >>> 8745485 表中已经存在的文件文件路径为users):

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

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

但是在$ new_file为空的情况下,您打算做什么?这是您需要考虑的问题。

,

通常,在调用确实写入方法的if语句中会遇到该错误。