【问题标题】:passing an array as an argument error in php在php中将数组作为参数传递错误
【发布时间】:2017-07-19 18:06:05
【问题描述】:

我是 php 新手,我遇到了问题,我必须在 php 函数中传递一个数组作为参数,当我这样做时,我得到数组到字符串的错误。你们能帮帮我吗??

这是辅助函数:

  private function userinfo($info,$args=''){
            try{
                if($args===''){
                    return $this->user->authenticate($this->username,$this->pswd,$info);
                }
                return $this->user->authenticate($this->username,$this->pswd,$info,$args);
            }catch(exception $e){


            }
        }

这是调用的添加函数:

   public function addUser($id,$email,$name){
        $this->userinfo('add',array(0=>$id,1=>$email,2=>$name));
    }

【问题讨论】:

标签: php arrays


【解决方案1】:

您在函数参数中定义了一个字符串,但将一个数组传递给函数,请修改您的代码,如下所示:

 private function userinfo($info, $args = []) {
   try {
     if (!is_array($args) {
       return $this->user->authenticate($this->username, $this->pswd, $info);
     }
     return $this->user->authenticate($this->username, $this->pswd,$info, $args);
   } catch(exception $e) {

   }
}

【讨论】:

  • 你仍然可以传递任何你想要的,这只是 default 值。如果您需要特定类型的变量,它看起来像function userinfo($info, array $args = []) {。错误来自该变量在代码中的使用方式。
  • 我试过这种方式,但我仍然收到数组到字符串错误
【解决方案2】:

试试这个:

 private function userinfo($info,$args = array()){
            try{
                if(empty($args)){
                    return $this->user->authenticate($this->username,$this->pswd,$info);
                }
                return $this->user->authenticate($this->username,$this->pswd,$info,$args);
            }catch(exception $e){


            }
        }



   public function addUser($id,$email,$name){
        $this->userinfo('add',array(0=>$id,1=>$email,2=>$name));
    }

【讨论】:

  • 我觉得你应该把$args改成$args = array(),这样就完美了
  • 我尝试过这种方式,但仍然出现数组到字符串错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-01
  • 2010-10-19
  • 1970-01-01
  • 1970-01-01
  • 2011-08-12
  • 2016-09-26
相关资源
最近更新 更多