php函数返回引用示例

时间:2022-09-30 15:28:57
<?php

class Test
{
	public $userCache;

	public function init()
	{
		for($i = 0; $i < 5; $i++)
		{
			$user = array(
				'name'	=> "joe$i",
				'age'	=> 23 + $i,
			);
			$this->userCache[] = $user;
		}
	}

	public function displayArray($arr = '')
	{
		if( gettype($arr) !== 'array' )
			$arr = $this->userCache;

		foreach($arr as $k => $v)
		{
			echo "$k: ";
			print_r($v);
			echo "\n";
		}
	}

	public function &getUser($uid)			// 函数返回引用
	{
		if( isset($this->userCache[$uid]) )
		{
			return $user = &$this->userCache[$uid];	// $user取引用(此处不能断)
		}
		else
		{
			echo "create a new user:\n";
			$user = array('name'=>'xxy', 'age'=>66);
			$this->userCache[$uid] = $user;
			return $user = &$this->userCache[$uid];
		}
	}

	public function modifyUser($uid)
	{
		//$user = $this->getUser($uid);		// 非引用调用
		$user = &$this->getUser($uid);		// 引用调用
		$this->displayArray($user);

		echo "------------------\n";
		$user['name'] = 'jjoe';				// 修改返回值
		$this->displayArray($user);
		$this->displayArray();				// 这里可看到被引用的对象值已被修改
	}

}

$a = new Test();
$a->init();
$a->modifyUser(12);

  

运行结果:

[zcm@vm-fedora20 server]$ php test.php 
create a new user:
name: xxy
age: 66
------------------
name: jjoe
age: 66
0: Array
(
    [name] => joe0
    [age] => 23
)

1: Array
(
    [name] => joe1
    [age] => 24
)

2: Array
(
    [name] => joe2
    [age] => 25
)

3: Array
(
    [name] => joe3
    [age] => 26
)

4: Array
(
    [name] => joe4
    [age] => 27
)

12: Array
(
    [name] => jjoe
    [age] => 66
)