SQL PHP HTML ASP JavaScript articles and free scripts to download
 

Getting global variable inside Functions in PHP

Many times we will not get the value of the variables inside a function to use. The reason is that the variables became local inside the function so variables declared outside the function will not be available inside the function for use. Also the variables used inside the function will not be available for the main script to use. For this return statement is to be used.

We can also pass the variables into the function by using arguments. To use the variables of main script inside the function we have to make them global first. Here is the code explaining how variables can be declared inside the function as global.

<?
$v1="Hello 1";
function test(){
echo "The value of \$v1= $v1";
// The above line will print The value of $v1=
global $v1;
echo "<br>The value of \$v1= $v1";
// The above line will print The value of $v1= Hello 1
$v2="Hello 2";
}
test();
echo "<br>The value of \$v2=$v2";
// The above line will print The value of $v2=
?>


Discuss this tutorial at forum


Further readings
PHP Function
Declaring variables as global inside the function
Returning variable from a function
Returning an array from a function to main script
Array as input to a function








 

Subscribe
Submit your email address and receive article and product notifications. Your email is safe with us.

Scripts
PHP
JavaScript
PHP Tutorials
Functions
PHP Sections
PHP Introduction
Loops & structure
Array
Date & Time
Functions
Form Handling
File Handling
Math Functions
String Functions
GD Functions
Comment Posting
Content Management
PHP & Ajax
Popular Tutorials
Drop down list
File Upload
Signup script
Member Login
Line Graph
PHP MySQL Paging
PHP Calendar
Subscribe
Submit your email address and receive article and product notifications. Your email is safe with us.