I would like to be able to output the name of a variable, along with that variable’s value. My use case is something close to a debug situation, but I’m actually building a proof of concept for other developers and managers so we can talk about things like input filtering. Anyway…
The output HTML is currently a table, but that shouldn’t matter. I can of course, just print out the name and then the contents in the HTML, but that gets tedious and is prone to typing errors. I’d like a function that I could call with the variable name, or a string with the variable name as the argument, and have that function generate the appropriate HTML for display. This doesn’t appear to work.
This works:
<tr><td>$variable</td><td><?php print $variable?></td></tr>
This doesn’t:
function rowFromVar($varname) {
$result = "<tr>";
$result .= "<td>\$$varname</td>";
$result .= "<td>" . $$varname . "</td>";
$result .= "</tr>";
return $result;
}
// now in the HTML...
<table><?php print rowFromVar("variable");?></table>
The variable variable $$varname is always empty. Notice that I’m passing in the name of the variable as a string, rather than trying to pass in the variable itself and work with it. I know that there be dragons that way. Instead, I’m trying to pass in the name of the variable as a string, and then use a variable variable (yeah, I know) to return the value of the original variable. That appears not to work either, and I’m betting it’s a scope issue.
Is there any good way to accomplish what I’m looking for?
You need declare your variable
globalwithin the function so that it references the global version. Adding this line at the start of your function should fix the problem: