-1

Summary

I want a function to execute only if a certain variable is true, however it checks the status of the variable before it exists.

Code

At the top of my PHP page I have:

$debug = true;

At the bottom, among other functions I have:

function debug($message){
    echo ($debug ? "$message<br/>" : "");
}

And throughout the page I call:

debug("Debugging message here");

However, when I run the page with error reporting on, I get this error:

Notice: Undefined variable: debug in /examle.php on line 148

which references the middle line of the function.

Question

How can I make a function that prints data only if the variable $debug, which is called at the top of the page, is true?

Community
  • 1
  • 1
Ben
  • 8,894
  • 7
  • 44
  • 80
  • 2
    The variable `$debug` is [out of scope](http://www.php.net/manual/en/language.variables.scope.php) in the function `debug()`.... that's why we pass arguments to functions – Mark Baker Jul 03 '15 at 08:16
  • What you have found is a variable scope – Rizier123 Jul 03 '15 at 08:16
  • You can either send `$debug` as a parameter or use `global $debug;` inside your function. I'd recommend not using `global` – Alex Tartan Jul 03 '15 at 08:16
  • Why would you recommend not using `global`? Is there a third alternative that avoids me having to send it as a parameter each time the function is called? – Ben Jul 03 '15 at 08:17

1 Answers1

3
function debug($message){
    global $debug;
    echo ($debug ? "$message<br/>" : "");
}

You need to access the global var else it checks for a local one

Sam
  • 2,950
  • 1
  • 18
  • 26
  • 2
    The "corecter" way would be to pass `$debug` into the function rather than making in global. Just saying. – Andrei Jul 03 '15 at 08:18
  • Why is making a variable global bad practice? – Ben Jul 03 '15 at 08:18
  • There's nothing wrong with making it global, obviously, the word `global` is there for a reason. It just hides dependencies, makes debugging a little harder too. But then again this is a little subjective. It's your call I guess. – Andrei Jul 03 '15 at 08:20