note 129380 added to language.references.spot
| From: | biziclop | Date: | Sun, 07 Apr 2024 17:54:08 +0000 |
| Subject: | note 129380 added to language.references.spot | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-221276@lists.php.net to get a copy of this message | ||
Here is another function for checking if two variables refer to each other.
The function by BenBE works properly, but it's very long and maybe slow.
This is a shorter, faster and hopefully bug-free alternative.
Works at least from PHP 4.3.0 to 8.3.4: https://3v4l.org/5JNSl
<?php
function is_same_ref( & $a, & $b ){
// Save original values
$ori_a = $a;
$ori_b = $b;
// Give them different values
$a = 1;
$b = 2;
// Compare them, if they're equal, they are references to each other
$eq = $a === $b;
// Restore original values
$a = $ori_a;
$b = $ori_b;
return $eq;
}
$a = array(1,2);
$b =& $a;
$c =& $a; // to check for side effects
var_dump( is_same_ref( $a, $b ));
// bool(true)
$a[] = 3;
$b[] = 4;
// After juggling our array in various ways inside is_same_ref(),
// all three variables still refer to the very same array:
var_dump( implode( $a ), implode( $b ), implode( $c ));
// string(4) "3456"
// string(4) "3456"
// string(4) "3456"
?>
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.13.131 (proxied: 85.238.90.216)
----
Manual Page -- https://php.net/manual/en/language.references.spot.php
Edit -- https://main.php.net/note/edit/129380
Del: integrated -- https://main.php.net/note/delete/129380/integrated
Del: useless -- https://main.php.net/note/delete/129380/useless
Del: bad code -- https://main.php.net/note/delete/129380/bad+code
Del: spam -- https://main.php.net/note/delete/129380/spam
Del: non-english -- https://main.php.net/note/delete/129380/non-english
Del: in docs -- https://main.php.net/note/delete/129380/in+docs
Del: other reasons-- https://main.php.net/note/delete/129380
Reject -- https://main.php.net/note/reject/129380
Search -- https://main.php.net/manage/user-notes.php