How to find out where a variable has been initialized or changed

Is there any way in PHP to know where a variable was initialized, or to assign a value the first time, or where it was last changed?

I think it should be possible to know because PHP gives such a hint of errors. For example:Can not redeclare abc() (previously declared in /path/to/file.php)

EDIT: I need this because:

function abc() {
   global $page; //this should be int.
   if($page == 2) { ... }
}

      

But when this function is running; I am getting error Can not convert object into int

. This is because some of which in my $$ page is being overridden by some object. I need to find the place where it was changed. Or I'll have to dig through all the code.

+3


source to share


2 answers


You can find out which object is assigned to the $ page variable using php's built-in get_class () function:

get_class($page);

      

You usually want to debug this with a unit test where you have to check that the $ page variable is numeric.

If you just want to debug on screen try:



if(is_object($page)){
     die(get_class($page));
    }

      

or through an exception:

if(is_object($page)){
 throw new Exception('$page must be numeric object given of type : '.get_class($page));
}

      

This will help you figure out which object is being assigned to your variable and just point you in the right direction.

0


source


If you want to know where a variable was defined, you're out of luck; there is no way to find this other than actually looking at the code and looking for it.

Your problem is that you are resolving the variable into a function (using global

). Since the variable is defined outside of the function, it can be changed at any time. If you want to always know what a variable contains, you must pass it instead of an argument:

$page = 2;
function abc($page) {
   if($page == 2) { ... }
}
$test = abc($page);

      



If you want to make sure that the value of a variable is a number, you can find that simply by checking the argument (or variable global

for that matter):

if (is_int($page) or ctype_digit($page)) {
    echo 'The $page variable is a number';
} else {
    echo 'The $page variable is NOT a number';
}

      

0


source







All Articles