【问题标题】:Return concatenated string from function in PHP从 PHP 中的函数返回连接的字符串
【发布时间】:2014-09-06 19:45:13
【问题描述】:

在 PHP 中,我创建了一个数组来存储需要以多种方式多次连接的值,因此创建了一个伴随函数来在需要时执行连接。但是,该函数似乎不会返回数组的值,而是会返回字符串的纯文本部分:

$my_array = array ("id" => "test");

$test = "First part " . $my_array['id'];
echo $test;   // <-- returns "First part test"

function concatenate(){
           $test_2 = "First part " . $my_array['id'];
            return $test_2;     
}

$use_function = concatenate();
echo $use_function;  // <-- returns "First part". Does not include array information.

任何关于为什么会发生这种情况的想法或解决此问题的更好方法将不胜感激。谢谢。

【问题讨论】:

  • 因为它是在函数之外定义的
  • 你的函数不知道 $my_array。将数组作为参数传递 concatenate($my_array)

标签: php arrays return echo concatenation


【解决方案1】:
$my_array = array ("id" => "test");

$test = "First part " . $my_array['id'];
echo $test;   // <-- returns "First part test"

function concatenate($my_array){
           $test_2 = "First part " . $my_array['id'];
            return $test_2;     
}

$use_function = concatenate($my_array);
echo $use_function;

这是一个小错误..调用函数时请小心..

【讨论】:

    【解决方案2】:

    你不能在这个函数中使用 $my_array 变量!您必须将其设为以数组为参数的全局 OR 调用函数:

    功能: function concatenate($arr, $string = "First Part "){ return $string . $arr['id']; }

    电话:concatenate($my_array);

    【讨论】:

      【解决方案3】:

      试试这个

      $my_array = array ("id" => "test");
      
      function concatenate($my_array){
                 $test_2 = "First part " . $my_array['id'];
                  return $test_2;     
      }
      
      $use_function = concatenate($my_array);
      echo $use_function;
      

      输出:

      First part test
      

      【讨论】:

        【解决方案4】:

        尝试使用此代码

        $my_array = array ("id" => "test");
        $test = "First part " . $my_array['id'];
        echo $test;   // <-- returns "First part test"
        
        function concatenate($myArray){
                   $test_2 = "First part " . $myArray['id'];
                    return $test_2;     
        }
        
        $use_function = concatenate($my_array);
        echo $use_function;
        

        或者如果这个函数在一个类中,你可以在你的函数中使用它:

        $test_2 = "First part " . $this->my_array['id']
        

        您的函数不知道 my_array['id'] 这就是它无法返回任何内容的原因

        【讨论】:

        • 如果函数在一个类中,它仍然不可能从对象上下文中调用 $my_array,如果它被声明为你所显示的
        猜你喜欢
        • 2023-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-14
        • 2021-10-11
        • 1970-01-01
        • 1970-01-01
        • 2021-05-12
        相关资源
        最近更新 更多