免费邮箱 |加入收藏 | 会员中心 | 我要投稿 | RSS
您当前的位置:首页 > PHP专区 > PHP技巧

引用的解释

时间:2011-05-16 15:55:22  来源:站内  作者:潘春会

    $tmpi = $this->i;
    modify1 ($tmpi);
    $this->i = $tmpi;
  }

  function corrupt2(){
    modify2 ($this->i);
  }

  function doNotCorrupt2(){
    $tmpi = $this->i;
    modify2 ($tmpi);
    $this->i = $tmpi;
  }

}

$functions = array ('corrupt1', 'corrupt2', 'doNotCorrupt1', 'doNotCorrupt2');

foreach ($functions as $func){

  $original = new a;

  ### Load some data in to the orginal with one of the four $functions
  $original->$func();

  $copy = $original;

  $copy->i->property = "Changed after the copy was made.";

  echo "n{$func}: $original->i->property = '" . $original->i->property . "'";
}

The script generates output:

corrupt1: $original->i->property = 'Changed after the copy was made.'
corrupt2: $original->i->property = 'Changed after the copy was made.'
doNotCorrupt1: $original->i->property = 'Original Value'
doNotCorrupt2: $original->i->property = 'Original Value'

rlynch at lynchmarks dot com (18-May-2005 05:51)

 

 

 

And, further...

<?php
    $intSize
= sizeof($arrData);

    for(
$i = 0; $i < $intSize; $n++) {
      
// Do stuff
   
}
?>

Can be shortened even further by using the often overlooked 'decrement until zero' concept.  I don't much like decrementing to get a job done, but it can make a lot of sense when the evaluation-of-doneness is time-costly:

<?php
   
for($i = sizeof($arrData); $i-- > 0 ; ) {
       
// Do stuff  
   
}
?>

One less variable to toss on the heap.  NOTE that rather inconveniently, the $i goes to and hits zero only in the case where it starts out positive.  When it is zero to begin with, it will become -1.  Bug or feature?  I've used it as a feature as a quick test of whether the $arrData array was empty to begin with.  If you don't plan on using $i after the loop for anything, it makes no difference.

If you need to be doing something ascending-sequential though, then the temporary variable suggestions that others have made makes the most sense.

Finally (and important) ... if the $arrData array is somehow being dynamically modified in size due to the //Do-Stuff routine underneath, then you may have little-to-no recourse except to use the sizeof() method/function in the loop.  Or, keep up the temporary variable in the loop as you push and pop things into and off the array. 

(sigh... this is the notable failing of deeply linked internal data structures: to figure out the size of any linked list of arbitrarily composed elements, the entire array needs to be "walked" every time the sizeof() or count() method is used.  But compared to the flexibility of associative arrays, the cost is mitigated by careful use.)

GoatGuy

nslater at gmail dot com (16-Mar-2005 11:12)

 

 

 

来顶一下
返回首页
返回首页
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表
推荐资讯
如何找出DHCP地址池里未使用的IP地址
如何找出DHCP地址池里
国内常用的DNS列表
国内常用的DNS列表
Linux邮件服务器软件比较
Linux邮件服务器软件比
学用纯CSS打造可折叠树状菜单
学用纯CSS打造可折叠树
相关文章
栏目更新
栏目热门