2013-03-31 41 views
6

为什么PHP不能将一个指向值保存为一个全局变量?一个PHP全局变量可以设置为一个指针吗?

<?php 
    $a = array(); 
    $a[] = 'works'; 
    function myfunc() { 
     global $a, $b ,$c; 
     $b = $a[0]; 
     $c = &$a[0]; 
    } 
    myfunc(); 
    echo ' $b '.$b; //works 
    echo ', $c '.$c; //fails 
?> 
+0

看到这个页面http://stackoverflow.com/questions/746224/are-there-pointers-in-php –

回答

4

FROM PHP Manual

警告

如果分配给一个变量的引用声明的 函数内部全球,参考将可见只在函数内部。你可以通过使用$ GLOBALS数组来避免这种情况。

...

想想全球是$ var;作为$ var = & $ GLOBALS ['var'];的快捷方式。 因此,为$ var分配另一个引用只会改变本地的 变量的引用。

<?php 
$a=array(); 
$a[]='works'; 
function myfunc() { 
global $a, $b ,$c; 
$b= $a[0]; 
$c=&$a[0]; 
$GLOBALS['d'] = &$a[0]; 
} 
myfunc(); 
echo ' $b '.$b."<br>"; //works 
echo ', $c '.$c."<br>"; //fails 
echo ', $d '.$d."<br>"; //works 
?> 

欲了解更多信息,请参阅: What References Are NotReturning References

0

PHP不使用指针。这本手册解释了究竟是什么引用,做什么和不做什么。您的例子specificly这里解决: http://www.php.net/manual/en/language.references.whatdo.php 要达到什么样的你正在尝试做的,你必须求助于$ GLOBALS数组,像这样,通过手动解释说:

<?php 
$a=array(); 
$a[]='works'; 
function myfunc() { 
global $a, $b ,$c; 
$b= $a[0]; 
$GLOBALS["c"] = &$a[0]; 
} 
myfunc(); 
echo ' $b '.$b; //works 
echo ', $c '.$c; //works 
?> 
0

在MYFUNC()使用全球$ a,$ b,$ c。

然后分配$ C = & $一个[0]

参考仅是内部MYFUNC可见()。

来源: http://www.php.net/manual/en/language.references.whatdo.php

“想一想全球$变种;作为快捷方式是$ var = & $ GLOBALS [ '变种'] ;.因此分配另一个引用是$ var只改变局部变量的参考。 “

+0

@Ultimater和Akam在我之前得到了:)干杯 –

相关问题