PHP Questions Home
Categories
Arrays
Files
Forms
Creating PDFs
PHP Errors
Functions
Images
MySQL
Numbers
Others
Strings
Website

PHP Forums
Forums Index
MySQL Forum
PHP Forum
Flash/Actionscript
Javascript
Web design

More PHP
PHP Functions
Top Questions
Ask a Question
PHP Interview Questions
PHP Jobs
Ecommerce
IT Questions
Business Websites

Sponsors

sponsor ad
My Salary
PHP Developer Salary
Advertise Here

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.



ASK A QUESTION

More functions PHP Questions

Hello, My question is about general practices. With classes, is error handling usually done inside of the class' functions, or would you just do the bare bones amount of work in the class, and then do error checking when you use the function elsewhere?

I'm trying to replace multipl occurences of "[nuber_goes_here]" in a string using preg_replace. $string = 'This is a sentence with a [25] in it.'; echo $string.''; $pattern = '/(\[)(\d+)(\])/'; $replacement = ' '.return_name(

Is there a way to use readfile() and not have it display the byte number at the bottom?

Hi; I had an email from my hosting company which said that my account was hacked and one script in images folder is trying to send thousands of spams(file name : "/public_html/images/sm5vy7.php"). they blocked my account and asked me to check

How do I return a value from a function?



Custom Search