Portfolio
Tutorials

PHP Tutorial

Info Store variables in a function
Nov 22nd, 05 • Views: 9251
A simple tutorial made to show you how to keep a variable in a function, even after the function has been executed.

This tutorial will show you how to store a variable in a function OOP style. It's very simple to do this, but knowledge of PHP is required to fully understand this tutorial (not much, but some).

First, a little background reference. Most people notice that any variables set in a function do not appear outside of the function (meaning you can call the function, then echo a variable from with-in it, and nothing will happen). So unless you pass a variable by reference using the ampersand '&', or return some value, you can't get much out of a function.
So there's a very simple way to fix this. Use the word "static". Simply take a look at the following example script for a better understanding. And don't worry if you don't understand it, the orange comments are there to help you know what it does.
<?php
/* First we create the function.  It takes 1 optional parameter $y.
   $y is used to demonstrate the difference between a regular variable, and a static one. */
function remember($y=0){
	/* Now the fun part.  Telling the function to remember 1 variable $x. */
	static $x;
	/* Increment $y */
	$y++;
	/* Make $x equal to $x+$y */
	$x += $y;
	/* Display the results */
	echo 'x = '.$x."\n"
		.'y = '.$y."\n";
}
 
/* Now we run some tests to see if everything works right */
echo remember()."\n";
echo remember()."\n";
echo remember()."\n";
echo remember()."\n";
/* For fun, make $y = 5 */
echo remember(5);
?>

Now, if you run the above example script as-is, what you see on screen should look something like:
x = 1
y = 1

x = 2
y = 1

x = 3
y = 1

x = 4
y = 1

x = 10
y = 6
If it doesn't, then you changed something, or you need to get a better version of PHP.
Also note, it's not recommended that you use this method to simply get a variable from place to place. There are other, more efficient methods to do that.