PHP: check if object/array is a reference

后端 未结 5 2038

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:57

    You can test for references in a multi-dimensional array by making a copy of the array, and then altering and testing each entry in turn:

    $roomCopy = $room;
    foreach ($room as $key => $val) {
      $roomCopy[$key]['_test'] = true;
      if (isset($room[$key]['_test'])) {
        // It's a reference
        unset($room[$key]);
      }
    }
    unset($roomCopy);
    

    With your example data, $room['furniture'] and $roomCopy['furniture'] will be separate arrays (as $roomCopy is a copy of $room), so adding a new key to one won't affect the other. But, $room['users'] and $roomCopy['users'] will be references to the same $users array (as it's the reference that's copied, not the array), so when we add a key to $roomCopy['users'] it is visible in $room['users'].

提交回复
热议问题