作为程序员一定要保持良好的睡眠,才能好编程

php参数传递中的一个特例-对象默认是引用传递

发布时间:2019-04-19

工作中,使用参数传递这是很正常的一件事情,那么在php中对象引用传递还是值传递?



下面来看一个实例:

$x = new stdClass();
$x->prop = 1;

function f ( $o ) // Notice the absence of &
{
  $o->prop ++;
}

f($x);

echo $x->prop; // shows: 2
?>

This is different for arrays:

<?php
$y = [ 'prop' => 1 ];

function g( $a )
{
  $a['prop'] ++;
  echo $a['prop'];  // shows: 2
}

g($y);

echo $y['prop'];  // shows: 1

从上的例子中很容易就可以看出来,stdClass 这是一个对象,对象在php中的传递默认就是引用传递。


其他类型都是值传递,如果其他类型需要引用传递,在变量前边 添加  & 这个符号即可。



举例说明下

function sum(&$num){
    
    return ++$num;
}

$n=10;

echo sum($n);