点击链接加入我的朋友圈

MENU

今天遇到有趣的php引用题目

April 5, 2020 • Read: 340 • 折腾

原文:

function refArray(&$arr)

{
    var_dump($arr);
    $refs = [];
    foreach ($arr as $key => $value)
        $refs[$key] = &$arr[$key];
    var_dump($refs);
    return $refs;
}

$arry = [3, "hello", 0.8, null];
$referenceArray = refArray($arry);
echo "----------------------\r\n";
var_dump($arry);
var_dump($referenceArray);

function refArray($arr)
{
    var_dump($arr);
    $refs = [];
    foreach ($arr as $key => $value)
        $refs[$key] = &$arr[$key];
    var_dump($refs);
    return $refs;
}

$arry = [3, "hello", 0.8, null];
$referenceArray = refArray($arry);
echo "----------------------\r\n";
var_dump($arry);
var_dump($referenceArray);

如果没有将$arry 与函数的$arr进行引用赋值,那么传入的是$arry副本,返回之后副本就会被销毁,那么$refs 也就不再是引用赋值了,它所引用的副本没了。

Last Modified: April 7, 2020
Archives QR Code Tip
QR Code for this page
Tipping QR Code
Leave a Comment

5 Comments
  1. Nworm Nworm

    nmd,为什么不支持md

    1. @Nworm@(捂嘴笑)@(捂嘴笑)原生不支持吧

    2. @Nworm搞好了

  2. Nworm Nworm
    int main(void) {
        unsigned int ip  = 0x7002c2f2;
        int n = 1;
        int *i = &n;
        p(i);
        return 0;
    }
    
    void p(int i){
        printf("%d",*i);
    }
    int main(void) {
        unsigned int ip  = 0x7002c2f2;
        int n = 1;
        int *i = &n;
        p(i);
        return 0;
    }
    
    void p(int *i){
        printf("%d",*i);
    }

    @(滑稽)

    1. @Nworm???