Reputation: 1393
I'd like to be able to inquire my program as to what variable a variable is a reference of. Is there a way to do this? I looked in all the usual sources and couldn't find anything, perhaps my search terms were goofy. Thanks.
Upvotes: 1
Views: 100
Reputation: 21439
you can just compare references with === operator
Note: this only compares object references.
$obj1 = new DateTime();
$obj2 = $obj1;
if($obj2 === $obj1){
echo "Equal";
}else {
echo "Not Equal";
}
// Outputs Equal
$obj2 = new DateTime();
if($obj2 === $obj1){
echo "Equal";
}else {
echo "Not Equal";
}
// Outputs Not Equal
Upvotes: 3
Reputation: 48304
As far as I know, there's no direct way to test if two variables point to the same thing. Something like this might work:
function is_reference_of(&$a, &$b)
{
// if an object, use strict comparison
if (is_object($a)) return $a === $b;
// definitely not a reference to each other if they aren't the same value
if ($a !== $b) return false;
$tmp = $a;
if (is_array($a))
{
$a = 0;
// if $b is no longer an array, then it must be a reference to $a
$is_ref = !is_array($b);
}
else
{
$a = !$a;
// if $b is no longer equal to $tmp, then it must be a reference to $a
$is_ref = ($b !== $tmp);
}
// make sure to reset $a back to what it was
$a = $tmp;
return $is_ref;
}
$a = 0;
$b = 0;
is_reference_of($a, $b); // false
$b = &$a;
is_reference_of($a, $b); // true
Huge disclaimer: I haven't really thought this through carefully. There could be all sorts of side effects to doing something like the above. Consider this just a proof of concept to get you started
If you are always working with arrays or classes, you could try setting a temporary field or property in one and seeing if it exists in the other, etc. That would be less prone to errors than the above code that changes the entire variable.
Note that the order of the parameters in the above function does not matter.
Update: With objects, you can use ===
and skip the function altogether. I've updated the function slightly to detect what type of variable is being tested and react accordingly. The disclaimer still applies.
Upvotes: 0
Reputation: 20612
If you're dealing with objects, I believe ===
performs the test you want.
$obj1 = new Object;
$obj2 = $obj1;
echo ($obj1 === $obj2) ? 'same' : 'not same'; // same
$obj2 = new Object;
echo ($obj1 === $obj2) ? 'same' : 'not same'; // not same
Upvotes: 0
Reputation: 837
The only code I personally know is to directly query what a class is of, not to retrieve it:
if($var instanceof Your_Class) { }
If you know the variable is strictly a class, you can use:
get_class();
If you use the function on a non-object, it appears to return an E_WARNING. I'd suggest code such as this:
$class_known = false;
if(is_object($class))
{
$class_name = get_class($class);
$class_known = false;
}
if($class_known)
{
echo $class_name;
}
Upvotes: 0