Tag: variables

PHP Global Variables with Functions

Here we’re going to take a look at variables inside and outside of PHP functions. It is very easy to make one error with a function and have it return the wrong value. We’re going to make a simple function named “func1” which we’ll tweak a bit to show how variables are used inside and out of functions in PHP.

Here is our function, take a look and see if you can tell what the output of the function will be:

[code lang=”php”]

[/code]

The output is nothing right now. haha So if you thought it was anything but nothing, that’s wrong. The function has no code in it whatsoever right now, and the variable “$var” is set to equal the returned value of the function “func1().” Since the function does nothing, $var is equal to nothing. Easy enough. Now let’s work with some variables.

[code lang=”php”]

[/code]

Now, we have a parameter to our PHP function. A parameter is any variable that is defined within the function’s parentheses. You can have many parameters in your functions – seperated by commas – but it isĀ  a good idea to keep your functions organized and simple to their purpose. So we have $var as a parameter to func1(). You can use these to submit values through a function and work with them inside the function to return a different or desired value. Right now, the function func1() is just returning $var. So whatever is put through as $var initially, will be returned back as it was.

So this code will result in the output:

hello

Let’s say we want to have a global variable we can use in several functions. Global variables are defined as such within a function as previously defined variables outside the function. In the following code we’ll define $name as “Brian” and use it in two functions.

[code lang=”php”]
“;
echo $goodbye;

?>
[/code]

The output of this code will be:

Hello Brian!
Goodbye Brian!

You can use global variables with PHP pages you include on other PHP pages. For example if you have variables defined on one PHP page, in this example “variables.php,” you can call that page to another and globally define variables in your functions to work with them and return what you like.

Variables.php:
[code lang=”php”]

[/code]

Now on our page we are working on, we’ll call it “display.php,” we’ll call the page variables.php and use these variables in functions.

Display.php:
[code lang=”php”]

[/code]

The output of this code will be:

Hello Brian! Thanks for visiting bgallz.org.

Filed under: PHP, Tutorials, Web ProgrammingTagged with: , , ,