超越PHP PHP动态 | 经典文章 | CLASS | 相关下载 | 常见问题 | FORUM | WIKI | 在线手册
Site search:    
<取消引用安全>
Last updated: Fri, 22 Jun 2007

引用定位

许多 PHP 的语法结构是通过引用机制实现的,所以上述有关引用绑定的一切也都适用于这些结构。一些结构,例如引用传递和返回,已经在上面提到了。其它使用引用的结构有:

global 引用

当用 global $var 声明一个变量时实际上建立了一个到全局变量的引用。也就是说和这样做是相同的:

<?php
$var
=& $GLOBALS["var"];
?>

这意味着,例如,unset $var 不会 unset 全局变量。

$this

在一个对象的方法中,$this 永远是调用它的对象的引用。




add a note add a note User Contributed Notes
引用定位
berni at ask-us dot at
16-Jul-2003 12:07
Some corrections:

Here is the working function:
It's documented because now I understand it myself (-:
<?
function get_var_id(&$var) {
   /* first of all, we need an array to store
    * the checked references.
    */
   static $addr=array();
   /* in order to see if $var refers to the
    * same data as any of the previously
    * checked references, we have to record
    * their actual values.
    */
   foreach ($addr as $k=>$v) $addr[$k]['cmp']=$v['ref'];
   /* now if the value of $var is changed,
    * we know exactly that any recorded
    * reference that changed in the same way
    * must refer to the same data.
    *
    * copy the DATA $var refers to ! */
   $sav = $var;
   /* replace the original DATA of $var
    * with "find refs to ".$var
    * after this operation, $var refers to
    * the same DATA as before ! */
   $var = "find refs to ".$var;
   /* look for changed values. */
   foreach ($addr as $k=>$v) {;
       /* skip arrays and objects because
        * of backreferences: == would fail!
        * BESIDES: we changed DATA to a
        * string, so this one cannot refer
        * to the same data.
        */
       if (is_array  ($v['ref'])) continue;
     if (is_object ($v['ref'])) continue;
       if ($v['ref']!==$v['cmp']) {
           /* this one changed! */
         $return=$k;
           /* because we won't record the
           * reused reference, we don't
            * need to look further.
          * every DATA can only have 1
            * reference in $addr!
            */
           break;
       }
   }
  /* copy original DATA of $var back.
    * now all references refer to the
    * original data again.
    */
   $var = $sav;
   /* record only new references! */
   if (!isset ($return)) $addr[]=array('ref'=>&$var);
   /* return the id. */
  return count ($addr);
}
?>

... now if you take out the comments, this is just a few lines.

PS: Excuses for my previous post. I got things mixed up because I'm used to Perl (with a complete different implementation of references)
tlesinsk at ec-lyon dot fr
08-Mar-2002 02:02
Note that you can't declare a global in a function and initialize it with :

global $foo = "bar";

you must :

global $foo;
$foo = "bar";

<取消引用安全>
 Last updated: Fri, 22 Jun 2007
view source | feedback | send page | sitemap | aboutus   
Copyright ® 2002-2003 PHPE.NET. All rights reserved
Last updated:2002-11-22