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

      

      

  • 相关阅读:
    webpack基本使用
    vue-路由-显示名称
    vue-父组件和路由
    vue-路由
    vue-父子组件和ref
    vue-组件
    go-面向对象编程(上)
    JavaScript的历史
    vue-列表动画
    钩子函数实现小球弹落
  • 原文地址:https://www.cnblogs.com/joeblackzqq/p/5106394.html
Copyright © 2020-2023  润新知