Reputation: 4601
Is there a way to achieve the following?
$myvar = 'x';
debug($myvar);
// outputs the following
// myvar value is x
Obviously, for this to happen, the debug function needs to be able to get the variable name passed to it.
Is there a magic constant for that? And if there isn't, please recommend alternative ways that would simplify the debugging.
Of course, I'm aware of the option where you pass the variable name as a separate argument,
debug('myvar',$myvar);
but my goal is exactly avoid doing that.
Upvotes: 4
Views: 213
Reputation: 5305
There is also great Google Chrome extension PHP Console with php library that allows to:
Recommend everyone!
Upvotes: 1
Reputation: 95
this is known as print debugging and considered as a very inefficient way for at least four reasons: you waste your time adding and then removing debugging code, debugging code slows down your web, not only the process where you're debugging, you can forget to remove the code after debugging is finished, it's takes time to find and analyze the results -- you see them in the continuous log(s) on the server. A better aproach is to install special debugger extension and work with your code from an IDE inteded for php like PHPEd
Upvotes: 0
Reputation: 137290
Yes, there is, but you will need to pass the name instead:
function debug($var_name) {
printf('%s value is %s', $var_name, var_export($GLOBALS[$var_name], true));
}
or, if you want only value without the parsable formatting:
function debug($var_name) {
printf('%s value is %s', $var_name, $GLOBALS[$var_name]);
}
Attention: This works only for variables in global scope. To do the same for local scope, you will probably need a solution employing get_defined_vars()
, like that:
printf('%s value is %s', $var_name, get_defined_vars()[$var_name]);
This cannot be simply enclosed within debug()
function. This is because get_defined_vars()
returns array representing variables in the scope where get_defined_vars()
is called, and we do not need the scope where debug()
is defined, don't we?
Unified solution could use global scope as default, but also accept some array representing local scope, so the definition could be:
function debug($var_name, $scope_vars=null) {
if ($scope_vars === null) {
$scope_vars = $GLOBALS;
};
printf('%s value is %s', $var_name, var_export($scope_vars[$var_name], true));
}
and then you can call it like that in global scope:
debug('myvar');
or like that in local scope, passing local scope array:
debug('myvar', get_defined_vars());
For working example see this demonstration: http://ideone.com/NOtn6
Does it help?
Upvotes: 2