【问题标题】:change a variable's value in a function when the variable is the arguement当变量是参数时,在函数中更改变量的值
【发布时间】:2011-10-18 11:11:08
【问题描述】:

我对范围很熟悉,但没怎么用过。如果我通过在函数中使用 GLOBAL $variableName 知道变量名称是什么,我就知道如何在函数内部更改变量的值。

我正在编写一个传递 2 个参数的方法。第一个将接受一个包含字符串的数组,第二个将保存要执行的设置,例如用于加密和修剪以修剪空格的 md5。

有没有办法改变函数内第一个参数的值?或者您知道实现此目的的更好方法吗?

    function _Edit($string, $rules)
{
    #check if array
    if(is_array($rules)!=TRUE)
    {array_push($GLOBALS[debug], '<span class="error">_Edits second arguement must be an array</span>');}
    if(is_array($string)!=TRUE)
    {array_push($GLOBALS[debug], '<span class="error">_Edits first arguement must be an array</span>');}else
    {       
        #loop through the strings
        foreach ($string as $sk=>$sv)
        {
            #make changes based on rules
            /* order of rules is important. 
            the changes will be made in the order the rules are sent */
            foreach ($rules as $rv)
            {
                switch ($rv)
                {
                    case 'md5':
                        //$string[$sk] = md5($sv);
                                                    //GLOBALS[$string][$sk] = md5($sv);
                        break;
                }
            }
        }
    }
}

【问题讨论】:

    标签: php string function methods scope


    【解决方案1】:

    如果我理解正确,您想从函数内部更改函数外部第一个参数的值吗?为此,您必须通过引用传递,或者您可以只返回更新后的数组并覆盖原始值。

    http://php.net/manual/en/language.references.pass.php

    【讨论】:

      【解决方案2】:

      为什么不返回最终在函数中修改的数组?

      所以...

      $my_array = _Edit($my_array, $rules);
      

      在你的功能中你可以这样做:

      function _Edit($string, $rules) {
          ... your code ...
          ... modify $string ...
          return $string;
      }
      

      【讨论】:

      • 好的,这就是我应该做的。我没有意识到我可以使用返回的数组来更新数组。
      猜你喜欢
      • 2016-03-28
      • 2023-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-02
      • 2013-06-28
      相关资源
      最近更新 更多