Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Naming a variable ... 1

Status
Not open for further replies.

dbeezzz

Technical User
Nov 30, 2005
54
KR
So I want to include a simple test function in my php app that goes something like this
Code:
function test( &$value ){

echo ('<br><br> THE VALUE OF $VALUE IS:'.$value.'<br>');

}
I'll then call this at various points to output my variables on my webpage, just to see how everything is coming along.
What I want to do though is to output the name of the variable as well as it's value. So that when I call the function using something like this
Code:
test ($blog)

I get ...

THE VALUE OF BLOG IS :<value of blog here>
how do I access the name of a variable as well as it's value ?
I hope this isn't too obvious and I'm just missing something really easy here ... :)
 
I think the name of the variable will always be the name declared within the function. but you can use variable variables

if the variables are within the global scope of the script (i.e. not within a function), you could pass the name of the variable to the function and then retrieve its value.
i.e.
Code:
<?
$var1 = "testing";
$var2 = "testing 2";

showvar ('var1');
showvar ('var2'); 

function showvar($var)
{
  global $$var;
  echo "<br/><br/>";
  echo "the value of $var is ". ${$var}  ;
}
?>

if you're not in the global scope then you'd have to pass the name and the value of the variable in to the function:

Code:
<?
function setvariables()
{
$var1 = "testing";
$var2 = "testing 2";

showvar ('var1', $var1);
showvar ('var2', $var2); //note single quotes
}
function showvar($var, $val)
{
  echo "<br/><br/>";
  echo "the value of $var is $val";
}
?>

both of the above cater only for strings and simple variables. if you want to handle arrays etc try replacing the showvar function with something using var_dump()

Code:
<?
$var1 = array ("testing", "testing 2");

showvar ('var1');

function showvar($var, $val=NULL)
{
  echo "<div style=\"color:red; border-width:thin; background-color:lightblue;\">";
  echo "The following is information on $var: <br/>";
  echo "<pre>";
  if (is_null($val)):
   global ${$var};
   var_dump(${$var});
  else:
   var_dump($val);
  endif;
  echo "</pre>";
  echo "</div>";
  echo "<br/>";
}
?>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top