July 1, 2010

Temporary Variable

Question by Alex

I have a function that retrieves some data from the database, formats it as HTML and then stores this HTML into a variable, $output. The problem is that $output cannot be echoed on the screen now, only later, after other functions run. Also this data must be retrieved at this stage, not later.

So how can I call this $output variable in another function, after output to the screen has started?

Answer by Pekka

You could define $output in the main script, and import it into a function:

function output() 
 {  
   global $output;

This will probably work for your situation at hand. However, it is considered bad practice to use the global variable space with stuff like this, and rightly so. (Believe me, I’ve done it for years. 🙂

There are some other approaches that are better for long-term code quality and maintainability.

Global config array

You could either keep one global array for all global settings. Do this somewhere in your main script:

$config = array();
$config["output"] = "<html>.......</htmL>";
$config["user_language"] = "en";
.....

you import the configuration array into the function like so:

function output()
 { global $config;
   echo $config["output"];

Registry pattern

if you want to do some reading, you could use something more advanced like the Registry Pattern. The snippet shown here looks a nice example for a registry. The Zend Framework also has a class for this.

But things like a Registry are really, really advanced, and probably not necessary for you at this point. I would suggest using one central config array. Should the need for something more complex arise, the config array is easy to find and replace.

Context: Are global variables in PHP considered bad practice?

Answer by Starx

Use Session

For example:

session_start();
$query = '...........';
$result = mysql_query($query);
$_SESSION['mysqlResult'] = $result;

Now you can use it from any page at any time by simply calling like this

$myresult = $_SESSION['mysqlResult'];

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!