PHP: check if object/array is a reference

后端 未结 5 2034

Sorry to ask, its late and I can\'t figure a way to do it... anyone can help?

$users = array(
    array(
        \"name\" => \"John\",
        \"age\"   =         


        
5条回答
  •  清歌不尽
    2020-12-17 15:58

    The best I can manage is a test of two variables to determine if one is a reference to the other:

    $x = "something";
    $y = &$x;
    $z = "something else";
    
    function testReference(&$xVal,&$yVal) {
        $temp = $xVal;
        $xVal = "I am a reference";
        if ($yVal == "I am a reference")  { echo "is reference
    "; } else { echo "is not reference
    "; } $xVal = $temp; } testReference($x,$y); testReference($y,$x); testReference($x,$z); testReference($z,$x); testReference($y,$z); testReference($z,$y);

    but I doubt if it's much help

    Really dirty method (not well tested either):

    $x = "something";
    $y = &$x;
    $z = "something else";
    
    function isReference(&$xVal) {
        ob_start();
        debug_zval_dump(&$xVal);
        $dump = ob_get_clean();
        preg_match('/refcount\((\d*)\)/',$dump,$matches);
        if ($matches[1] > 4) { return true; } else { return false; }
    }
    
    var_dump(isReference($x));
    var_dump(isReference($y));
    var_dump(isReference($z));
    

    To use this last method in your code, you'd need to do something like:

    foreach($room as $key => $val) {
        if(isReference($room[$key])) unset($room[$key]);
    }
    

    because $val is never a reference as it's a copy of the original array element; and using &$val makes it always a reference

提交回复
热议问题