douzhai1182 2016-07-31 22:52
浏览 23
已采纳

如果提供参数,则创建全局变量

How do I create a global variable the way preg_match does for the $matches parameter?

In the following code, preg_match creates global $Hel_matches and $Wor_matches variables even though they're not defined.

$string = "Hello, World!";

$pattern1 = '/Hel/';
$pattern2 = '/Wor/';

preg_match($pattern1, $string, $Hel_matches);
preg_match($pattern2, $string, $Wor_matches);

print_r($Hel_matches);
print_r($Wor_matches);

I want to be able to do the same thing.

For example, odd_numbers() returns an array filled with the odd numbers between 0 and $max.

function odd_numbers($max) {
    $numbers = [];
    for ($i = 0; $i <= $max; $i++) {
        if ($i % 2 == 1) {
            $numbers[] = $i;
        }
    }
    return $numbers;
}

$odd_numbers = odd_numbers(10);
print_r($odd_numbers);

If I want to do some extra calculation in the odd_numbers() and also return that (for debug purposes, for example), well, I can't. I can only return one thing. So, instead, I pass a second argument (variable) to the odd_numbers() and the function returns/assigns the return value to that variable.

// $odd_numbers = odd_numbers(10, $evens); // fill $evens (if provided) with even numbers for debug purposes
print_r($odd_numbers);
// print_r($evens); // debug
  • 写回答

1条回答 默认 最新

  • dongzhu0327 2016-07-31 23:08
    关注

    You can use a reference by prefixing the variable with &:

    function odd_numbers($max, &$evens = array()) {
        // blah
        $numbers = array(1, 3, 5);
    
        if (func_num_args() == 2) {
            $evens = array(2, 4, 6);
        }
    
        return $numbers;
    }
    
    $odd_numbers = odd_numbers(10, $evens);
    var_dump($evens);
    

    Output:

    array (size=3)
      0 => int 2
      1 => int 4
      2 => int 6
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退