码迷,mamicode.com
首页 > Web开发 > 详细

php函数返回引用示例

时间:2016-01-06 19:38:42      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

<?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
)

  

  

php函数返回引用示例

标签:

原文地址:http://www.cnblogs.com/joeblackzqq/p/5106394.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!