Friday, October 28, 2011

PHP - Print any variable easily

You often need to print some PHP variable right into the HTML code, but the variable is out of your current scope. Familiar problem, isn't it?

Here is a bright solution: PHP function that prints any global variable:

function print_var($var = 'domain', $url = '')
  global $$var, $$$var;
  if ($url != '')
    echo("<a href=\"$url\">${$var}</a>");

Moreover, you can pass some URL as a second parameter, and your variable becomes a clicable link :)

Some examples:

<?php print_var('page')?>
<?php print_var('domain', '/') ?>
<?php print_var('software', '/download/') ?>
<?php print_var('author', '') ?>

No comments: