How do I know if two references point to the same instance?
Moderator: General Moderators
How do I know if two references point to the same instance?
How do I know if two references point to the same instance?
- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia
Be naughty and inject something into one then see if it's there in the other.
Code: Select all
function is_reference(&$o1, &$o2)
{
$prop_base = "_is_reference_test_var_";
$i = 1;
$prop = "";
do
{
$prop = $prop_base . $i;
$i++;
}
while (isset($o1->$prop) || isset($o2->$prop));
//Now we know $prop DOES NOT exist in $o1 or $o2
$o1->$prop = true;
$is_reference = isset($o2->$prop);
unset($o1->$prop);
return $is_reference;
}In php5 you can use ===
Code: Select all
$o1 = new stdClass;
$o2 = $o1;
$o3 = new stdClass;
echo '$o1===$o2 ', $o1===$o2 ? 'true':'false', "<br />\n";
echo '$o1===$o3 ', $o1===$o3 ? 'true':'false', "<br />\n";- Maugrim_The_Reaper
- DevNet Master
- Posts: 2704
- Joined: Tue Nov 02, 2004 5:43 am
- Location: Ireland
Re: How do I know if two references point to the same instan
===nadavvin wrote:How do I know if two references point to the same instance?
see http://de2.php.net/manual/en/language.o ... arison.php
Re: How do I know if two references point to the same instan
thanksvolka wrote:===nadavvin wrote:How do I know if two references point to the same instance?
see http://de2.php.net/manual/en/language.o ... arison.php
Code: Select all
Two instances of the same class
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : FALSE
o1 !== o2 : TRUE
Two references to the same instance
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSEHere is a hypothetical question..
How would I compare two objects and depict if they are the same class, have the same properties, and the same data, but are not the same instance?
Would it simply be:
How would I compare two objects and depict if they are the same class, have the same properties, and the same data, but are not the same instance?
Would it simply be:
Code: Select all
if ( (get_object_vars($obj1) === get_object_vars($obj2))
&& (get_class($obj1) === get_class($obj2) )
{
// ...I think this do it:How would I compare two objects and depict if they are the same class, have the same properties, and the same data, but are not the same instance?
Code: Select all
if ( ($o1 == $o2) && !($o1===$o2) )
{
}- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia