PHP报错:Cannot access offset of type string on string问题求助
问题:Cannot access offset of type string on string 错误解决
我在控制器中编写了如下代码:
$sign = array( "firstname" => $sign->firstname, "lastname" => $sign->lastname, ); $this->users($sign);
并在users方法中实现了以下逻辑:
public function users($sign) { $this->args = $this->getTemplateArgs(); $args = $this->args; $envelope_args = $args["envelope_args"]; # Create the envelope request object $envelope_definition = $this->makeEnvelopeFileObject($args["envelope_args"]); $envelope_id = $results->getEnvelopeId(); # Create the Recipient View request object $authentication_method = 'None'; $recipient_view_request = new \DocuSign\eSign\Model\RecipientViewRequest([ 'authentication_method' => $authentication_method, 'client_user_id' => '1000', 'recipient_id' => '1', 'return_url' => $envelope_args['ds_return_url'], 'user_name' => $sign['firstname'], ]); $result_test = $envelopeApi->getEnvelope($accountInfo[0]->getAccountId(), $args['envelope_ids']); $url = $results['url']; $json['data'] = $url; return Response::success(200, 'ok', $json); }
运行时触发错误:Cannot access offset of type string on string,错误出现在'user_name' => $sign['firstname']这一行,求解决。
问题分析与解决
错误原因
错误提示明确说明$sign是字符串类型,但你试图用数组下标$sign['firstname']访问元素,类型不匹配导致报错。根源在于控制器代码的变量名冲突:你用了和原对象相同的变量名$sign来定义数组,可能导致变量覆盖或赋值异常,最终传递到users方法的$sign不是预期的数组类型。
解决步骤
修复变量名冲突
把控制器中的数组变量名改为与原对象不同的名称,避免覆盖:// 重命名数组变量,避免和原$sign对象冲突 $signData = array( "firstname" => $sign->firstname, "lastname" => $sign->lastname, ); $this->users($signData);同步修改
users方法的参数名,并替换内部的引用:public function users($signData) { // ... 其他代码不变 $recipient_view_request = new \DocuSign\eSign\Model\RecipientViewRequest([ // ... 其他参数 'user_name' => $signData['firstname'], ]); // ... 后续代码 }添加类型校验
在users方法开头添加类型检查,提前拦截非法参数:public function users($sign) { if (!is_array($sign)) { throw new \InvalidArgumentException('参数$sign必须为数组类型'); // 或返回错误响应:return Response::error(400, '参数格式错误'); } // ... 后续代码 }验证原对象属性有效性
确保控制器中原始的$sign对象存在firstname和lastname属性,避免空属性导致数组赋值异常:if (empty($sign->firstname) || empty($sign->lastname)) { return Response::error(400, '缺少用户姓名信息'); } $signData = array( "firstname" => $sign->firstname, "lastname" => $sign->lastname, ); $this->users($signData);
内容的提问来源于stack exchange,提问作者Rubyjane
相关产品推荐
相关产品推荐

