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
    )
    

      

      

  • 相关阅读:
    项目01-nginx模块
    Spark机器学习
    项目01-手机端模块
    Spark内存管理
    Spark Streaming
    Spark SQL
    Spark Job调度
    Spark master节点HA配置
    机器学习
    07、Spark集群的进程管理
  • 原文地址:https://www.cnblogs.com/joeblackzqq/p/5106394.html
Copyright © 2011-2022 走看看