Detecting whether a PHP variable is a reference / referenced

后端 未结 5 1009
情书的邮戳
情书的邮戳 2020-11-27 05:33

Is there a way in PHP to determine whether a given variable is a reference to another variable and / or referenced by another variable? I appreciate that it might not be po

5条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 05:48

    Full working example:

    function EqualReferences(&$first, &$second){
        if($first !== $second){
            return false;
        } 
        $value_of_first = $first;
        $first = ($first === true) ? false : true; // modify $first
        $is_ref = ($first === $second); // after modifying $first, $second will not be equal to $first, unless $second and $first points to the same variable.
        $first = $value_of_first; // unmodify $first
        return $is_ref;
    }
    
    $a = array('foo');
    $b = array('foo');
    $c = &$a;
    $d = $a;
    
    var_dump(EqualReferences($a, $b)); // false
    var_dump(EqualReferences($b, $c)); // false
    var_dump(EqualReferences($a, $c)); // true
    var_dump(EqualReferences($a, $d)); // false
    var_dump($a); // unmodified
    var_dump($b); // unmodified
    

提交回复
热议问题