php的数组传值调用与传址调用

巴扎黑
发布: 2016-11-12 14:00:22
原创
1741 人浏览过

在java中数组的调用默认是是传址调用:主体方法中传递一个数组给某个方法,在该方法内修改了数组的某个值;回到主方法中会发现数组已经发生了改变;

测试代码:

public class ArrayTest { public static void main(String[] args){ Map[] maparray=new Map[3]; for (int i = 0; i < maparray.length; i++) { Map map=new HashMap(); map.put("a", i+"_ajkcz"); map.put("c", "werq_"+i); maparray[i]=map; } System.out.println("++++++++++++++++++++++++"); for (int i = 0; i < maparray.length; i++) { Map map=maparray[i]; Iterator it=map.keySet().iterator(); while(it.hasNext()){ String key=(String) it.next(); System.out.println(key+"\t"+map.get(key) ); } } System.out.println("++++++++++++++++++++++++"); new ArrayCharge().printAndChangeArray(maparray); System.out.println("++++++++++++++++++++++++"); for (int i = 0; i < maparray.length; i++) { Map map=maparray[i]; Iterator it=map.keySet().iterator(); while(it.hasNext()){ String key=(String) it.next(); System.out.println(key+"\t"+map.get(key) ); } } } } class ArrayCharge { public void printAndChangeArray(Map[] maparray){ for (int i = 0; i < maparray.length; i++) { Map map=maparray[i]; map.put("a",i+"________"); } for (int i = 0; i < maparray.length; i++) { Map map=maparray[i]; Iterator it=map.keySet().iterator(); while(it.hasNext()){ String key=(String) it.next(); System.out.println(key+"\t"+map.get(key) ); } } } } 控制台输出结果: ++++++++++++++++++++++++ cwerq_0 a0_ajkcz cwerq_1 a1_ajkcz cwerq_2 a2_ajkcz ++++++++++++++++++++++++ cwerq_0 a0________ cwerq_1 a1________ cwerq_2 a2________ ++++++++++++++++++++++++ cwerq_0 a0________ cwerq_1 a1________ cwerq_2 a2________
登录后复制

而在php中,数组的调用默认是传值调用,在字方法中修改了数组,在父方法中无法察觉

测试代码:

登录后复制


控制台输出:

Array ( [0] => Array ( [keystr] => key0 [valuestr] => value0 ) [1] => Array ( [keystr] => key1 [valuestr] => value1 ) [2] => Array ( [keystr] => key2 [valuestr] => value2 ) ) +++++++++++++++++++++++++ Array ( [0] => Array ( [keystr] => key0 [valuestr] => value0 ) [1] => Array ( [keystr] => key1 [valuestr] => value1 ) [2] => Array ( [keystr] => key2 [valuestr] => value2 ) ) +++++++++++++++++++++++++
登录后复制

如果希望在php中也能类似java中传数组参数给字方法,字方法处理完成后父方法中数组也跟随改变则需要在传递参数时不传递值而是传递值的指针,例如p的值是100,即$p=100;在传递p给字方法时需要传递的参数则为“&$p”

测试代码:

登录后复制


控制台输出:

Array ( [0] => Array ( [keystr] => key0 [valuestr] => value0 ) [1] => Array ( [keystr] => key1 [valuestr] => value1 ) [2] => Array ( [keystr] => key2 [valuestr] => value2 ) ) +++++++++++++++++++++++++ Array ( [0] => Array ( [keystr] => key0 [valuestr] => _________0 ) [1] => Array ( [keystr] => key1 [valuestr] => _________1 ) [2] => Array ( [keystr] => key2 [valuestr] => _________2 ) )
登录后复制


相关标签:
php
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!