2016-07-30 81 views
0

使用下面的代码不起作用,但当我使用

<?php 
    $GLOBALS['players'] = array(); 

    function add($name) { 
     $array = $GLOBALS['players'][$name] = array(); 
     array_push($array, "b"); 
    } 

    add("a"); 
    print_r($players); 
?> 

(输出:阵列([α] =>数组()))的这里代码

<?php 
    $GLOBALS['players'] = array(); 

    function add($name) { 
     $array = $GLOBALS['players'][$name] = array(); 
     array_push($GLOBALS['players'][$name], "b"); 
    } 

    add("a"); 
    print_r($players); 
?> 

(输出:阵列([α] =>数组([0] => b)))它工作正常。为什么$ array在引用同一个数组时不起作用。

+1

参见:http://stackoverflow.com/q/879/3933332 – Rizier123

回答

0

这很简单,当您将值传递给$array时,您将$GLOBAL数组传递给一个新变量,但您没有引用变量$GLOBAL变量。

简而言之:$array$GLOBAL是两个不同的变量。这样做就像是这样做的:

$a = 10; 
$b = $a; 
$b++; 
print_r($a); // Will not print 11, but 10, because you edited the var $b, that is different from $a. 

为了解决这个小麻烦您必须通过引用它喜欢这里的变量传递给$array

function add($name) { 
    $GLOBALS['players'][$name] = array(); 
    $array = &$GLOBALS['players'][$name]; 
    array_push($array, "b"); 
} 
+0

你介意告诉我什么在$ GLOBAL前加上&做什么? – Gensoki

+0

使用&传递变量的引用而不是该值的前缀变量,因此如果编辑传递引用的变量,则可以编辑引用的变量。看看这里请:http://sandbox.onlinephpfunctions.com/code/4c3cb0dd2197f4aa03885f4c37bd04ce755d80eb – Syncro

+0

哦,我明白了。谢谢。 – Gensoki