I created a function to allow me to debug PHP scripts so long as a variable ($debug
) is set to 1
:
function debug($msg) {
if ($debug == 1) {
echo $msg;
} else {
return false;
}
}
That way, at the top of my script (before the functions.php
file is called), I write:
$debug = 1;
to enable debugging, then:
debug("Function executed: " . $data);
at certain points so that I know string values/whatever at that point, with the desired response being the message displayed upon the screen.
However, regardless of what the value of the $debug
string is, I never see any echo
'd statements.
How can this be achieved?
It's difficult to say because you provided too few data.
The reason can be that your $debug
variable is not known inside a function. Because using global
s is not adviced, consider using constants define("DEBUG",1);
.
EDIT
I presented within another question how I use a class for doing the same thing as class names are also globally accessed.
Debug is not available to your function because it is out of scope. You either:
global
keyword to include it in your function (discouraged).
function debug($msg, $debug){
if($debug==1){
echo $msg;
} else {
return false;
}
}
or
function debug($msg){
global debug;
if($debug==1){
echo $msg;
} else {
return false;
}
}
The global variable is not accessible to functions until you make it so. Eg:
function debug($msg( {
global $debug;
etc...
PS: Please, don't do this. Find a better way. Really.
$debug is your global variable, so it is not accessible in your function
There is also the possibility to declare a const, (and then just insure the namespace is correct), like this:
const debug = true;
function newPrint($msg) {
if (\debug === true) {
echo $msg;
} else {
return false;
}
}
ewPrint("heey");//will print "heey"
so just dont use a variable, but use a const.