2013-03-31 40 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在我之前得到了:)乾杯 –

相關問題