开发者

change a variable's value in a function when the variable is the arguement

I am familiar with scope but have not used it much. I know how to change a variable's value inside of a function if I know what the variable name is by using GLOBAL $variableName in the function.

I'm writing a method that is passed 2 arguments. The first will accept an array that contains strings and the second will hold settings to do such as md5 for encrypting and trim to trim spaces.

Is there a way I can change the first argument's value inside the function? or do you know of a better method to accomplish this?

    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);
                                             开发者_如何学Go       //GLOBALS[$string][$sk] = md5($sv);
                        break;
                }
            }
        }
    }
}


If I understand right, you want to change the value of the first argument outside of the function from inside the function? for this you will have to pass by reference, or you can just return the updated array and overwrite the original value.

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


Why don't you return the array you eventually modified in your function?

So...

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

And in your function you do:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜