随笔 - 493  文章 - 0  评论 - 97  阅读 - 239万

php函数返回引用示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<?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);

  

运行结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
[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
)

  

  

posted on   清清飞扬  阅读(295)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET10 - 预览版1新功能体验(一)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示