zoukankan      html  css  js  c++  java
  • php函数返回引用示例

    <?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 "
    ";
    		}
    	}
    
    	public function &getUser($uid)			// 函数返回引用
    	{
    		if( isset($this->userCache[$uid]) )
    		{
    			return $user = &$this->userCache[$uid];	// $user取引用(此处不能断)
    		}
    		else
    		{
    			echo "create a new user:
    ";
    			$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 "------------------
    ";
    		$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
    )
    

      

      

  • 相关阅读:
    [从jQuery看JavaScript]-匿名函数与闭包(Anonymous Function and Closure)
    Oracle同义词总结
    Jquery定义对象( 闭包)
    jQuery基础总结
    jquery技巧总结
    C# 委托 事件
    OOP面向对象
    DNS服务器 和CDN
    反向代理服务器的工作原理
    c# EF code First生成数据库以及表
  • 原文地址:https://www.cnblogs.com/joeblackzqq/p/5106394.html
Copyright © 2011-2022 走看看