How do I make a variable from outside a function work in that function?
<?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.
Comment on this Question and Answer >>>
ASK A QUESTION
More functions PHP Questions
Hey, I need a php script to copy a complete directory to a new one (which is a variable). i.e www.webpage.com/example/ --> www.webpage.com/folder_just_created/. I've looked for hours KurtHow can I access information sent through $_GET on a form?
How can I access information sent through $_POST on a form?
What is a function?
Can we use include ("abc.php") two times in PHP page "makeit.php" ?
