PHP Questions Home

Categories

Arrays
Files
Forms
Functions
Images
MySQL
Numbers
Others
Strings
Website


PHP Functions

PHP Functions


More PHP

Top Questions
Ask a Question

How do I make a variable from outside a function work in that function?


This is done using the global keyword. Here is an example that you can copy and paste to see what happens when we try to use a variable within a function without using the global keyword and then when we do:

<?php
$data 
"Nothing to declare";
function 
nothing() { echo @"I have $data"; }
function 
todeclare() { global $data; echo "I have $data"; }
nothing(); echo "<br />"todeclare();
?>


This will print on the first line:
'I have'

and then on the next line

'I have Nothing to declare'

This illustrates that the global keyword is needed to allow the function to access its value from outside the function.

The '@' before the text in nothing supresses a PHP Notice error when it tries to echo an undefined variable.



More functions PHP Questions

How do I return a value from a function?
How do I get a variable in a function to retain its value between calls?
What is a function?
What is a static variable within a function?