【问题标题】:Can a PHP global variable be set to a pointer?可以将 PHP 全局变量设置为指针吗?
【发布时间】:2013-03-31 07:35:04
【问题描述】:

为什么 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
?>

【问题讨论】:

标签: php pointers global


【解决方案1】:

来自PHP Manual:

警告

如果您将引用分配给在 a 中声明为全局的变量 函数,引用将仅在函数内部可见。你 可以通过使用 $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

【讨论】:

    【解决方案2】:

    在 myfunc() 中,您使用全局 $a、$b、$c。

    然后你分配 $c =& $a[0]

    引用只在 myfunc() 中可见。

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

    “将全局 $var; 视为 $var =& $GLOBALS['var']; 的快捷方式。因此为 $var 分配另一个引用只会更改局部变量的引用。”

    【讨论】:

    • @Ultimater 和 Akam 在我之前得到它 :) 干杯
    【解决方案3】:

    PHP 不使用指针。该手册解释了确切的引用是什么,做什么和不做什么。您的示例在此处具体说明: 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
    ?>
    

    【讨论】:

      猜你喜欢
      • 2021-11-11
      • 2012-05-18
      • 2011-09-04
      • 2014-05-18
      • 1970-01-01
      • 2017-04-03
      • 2017-04-26
      • 1970-01-01
      • 2014-01-02
      相关资源
      最近更新 更多