- PHP Basics
- PHP Home
- PHP Environment Setup
- PHP Getting Started
- PHP Basic Syntax
- PHP echo
- PHP print
- PHP echo Vs print
- PHP Comments
- PHP Data Types
- PHP Variables
- PHP Variable Scope
- PHP gettype()
- PHP Constants
- PHP Operators
- PHP Program Control
- PHP Decision Making
- PHP if-elseif-else
- PHP switch
- PHP Loops
- PHP for Loop
- PHP while Loop
- PHP do-while Loop
- PHP foreach Loop
- PHP break & continue
- PHP Popular Topics
- PHP Arrays
- PHP print_r()
- PHP Strings
- PHP Functions
- PHP References
- PHP Object Oriented
- PHP Object Oriented
- PHP Classes & Objects
- PHP Member Variable
- PHP Member Function
- PHP Encapsulation
- PHP Data Abstraction
- PHP Inheritance
- PHP Constructor Destructor
- PHP Polymorphism
- PHP Web Developments
- PHP Web Developments
- PHP GET & POST
- PHP Read Requested Data
- PHP File Handling (I/O)
- PHP File Handling (I/O)
- PHP fopen() | Open File
- PHP Create a File
- PHP fwrite() | Write to File
- PHP fread() | Read File
- PHP feof()
- PHP fgetc()
- PHP fgets()
- PHP fclose() | Close File
- PHP unlink() | Delete File
- PHP Append to File
- PHP copy() | Copy File
- PHP file_get_contents()
- PHP file_put_contents()
- PHP file_exists()
- PHP filesize()
- PHP rename() | Rename File
- PHP fseek()
- PHP ftell()
- PHP rewind()
- PHP disk_free_space()
- PHP disk_total_space()
- PHP mkdir() | Create Directory
- PHP rmdir() | Remove Directory
- PHP glob() | Get Files/Directories
- PHP basename() | Get filename
- PHP dirname() | Get Path
- PHP filemtime()
- PHP file()
- PHP Advanced
- PHP Cookies
- PHP Sessions
- PHP Send Emails
- PHP Serialization
- PHP Namespaces
- PHP File Upload
- PHP Date and Time
- PHP Image Processing
- PHP Regular Expression
- PHP Predefined Variables
- PHP Error Handling
- PHP Debugging
- PHP and MySQLi Tutorial
- PHP and MySQLi Home
- PHP MySQLi Setup
- PHP MySQLi Create DB
- PHP MySQLi Create Table
- PHP MySQLi Connect to DB
- PHP MySQLi Insert Record
- PHP MySQLi Fetch Record
- PHP MySQLi Update Record
- PHP MySQLi Delete Record
- PHP MySQLi SignUp Page
- PHP MySQLi LogIn Page
- PHP MySQLi Store User Data
- PHP MySQLi Close Connection
- PHP connect_errno
- PHP connect_error
- PHP query()
- PHP fetch_row()
- PHP fetch_assoc()
- PHP fetch_array()
- PHP free_result()
- PHP error
- PHP prepare()
- PHP bind_param()
- PHP execute()
- PHP fetch()
- PHP store_result()
- PHP num_rows
- PHP bind_result()
- PHP get_result()
- PHP mysqli_result Class
- PHP Error Constants
- PHP mysqli_driver()
- PHP Misc
- PHP error_reporting()
- PHP Escape Special Characters
- PHP htmlspecialchars()
- PHP new
- PHP header()
- PHP getallheaders()
- PHP empty()
- PHP isset()
- PHP unset()
- PHP exit()
- PHP exit Vs break
- PHP include()
- PHP require()
- PHP include() Vs require()
- PHP AJAX & XML
- PHP AJAX
- PHP XML
- PHP File Handling Functions
- PHP abs()
- PHP Test
- PHP Online Test
- Give Online Test
- All Test List
PHP Variable Scope
This article is created to cover the topic, scope of a variable in PHP.
Variable scope in PHP is one of the important topic, as we must know whether:
- a variable defined outside a function can be accessed inside the function or not
- a variable defined inside the function, can be accessed from outside the function or not
- what to do, if we need to preserve the previous value of a variable defined inside a function
- and so on
Before starting the tutorial, let me tell you, there are following three variable scopes available in PHP:
- local
- global
- static
PHP Local Variable
Local variables in PHP are those variables that are defined within a function. And the scope of those variables are only to that particular function, where it is defined. For example:
<?php function codescracker() { $x = 500; echo $x; } codescracker(); ?>
The output produced by above PHP example is shown in the snapshot given below:
The variable $x defined inside the function named codescracker(), is only accessible to inside
the function. Now the question is, what if we try to access a local variable, from outside the function where it
is defined?
Let's find out, using the example given below:
<?php function codescracker() { $x = 500; } echo $x; ?>
This time, the output produced by above example, is:
The similar output, you will get, if you will try to access a local variable from outside the scope where the variable is defined.
PHP Global Variable
Global variables in PHP are those variables that are defined outside a function. And the scope of those variables are to everywhere except function(s). For example:
<?php $x = 10; echo "<p>The value of \$x is $x</p><hr>"; if($x>0) echo "<p>The value of \$x is greater than 0.</p><hr>"; echo "<p>Printing the value of \$x for five times:</p>"; for($i=0; $i<5; $i++) echo "$x<BR>"; ?>
The output of above PHP example, is:
Now the question is, what if we will try to access a variable declared outside a function, from inside a
function?
Let's find out, using an example given below:
<?php $x = 10; function codescracker() { echo $x; } codescracker(); ?>
Now the output produced by this example, is:
You will get similar output every time, when you will try to access a variable from inside a function, that is defined outside the function. But PHP has a solution to use global variables from inside the function. The solution is, the global keyword, that is defined right after this paragraph.
PHP global Keyword
Use global keyword to declare a global variable inside a function to be able to access that global variable, in this way:
function functionName() { global variableName; }
That is, use global keyword to declare all the global variables, inside the function where you want to use. For example:
<?php $x = 10; $y = 20; function codescracker() { global $x; echo "<p>The value of \$x is $x</p>"; global $y; echo "<p>The value of \$y is $y</p>"; $z = $x + $y; echo "<p>\$x + \$y = $z</p>"; } codescracker(); ?>
The output of above PHP example, is:
However, PHP stores all variables that are declared globally, in an array named $GLOBALS[variable]. Therefore, we can use this array to access and update a global variable from within a function. For example:
<?php $x = 10; $y = 20; function codescracker() { echo "<p>The value of \$x is ", $GLOBALS['x'], "</p>"; echo "<p>The value of \$y is ", $GLOBALS['y'], "</p>"; $z = $GLOBALS['x'] + $GLOBALS['y']; echo "<p>\$x + \$y = $z</p>"; } codescracker(); ?>
You will get the same output as of previous example. Let me create another example, where I'm going to update the global variable, from within the function:
<?php $x = 10; echo "<p>\$x = $x (before function, before update)</p>"; function codescracker() { echo "<p>\$x = ", $GLOBALS['x'], " (inside function, before update)</p>"; $GLOBALS['x'] = 20; echo "<p>\$x = ", $GLOBALS['x'], " (inside function, after update)</p>"; } codescracker(); echo "<p>\$x = $x (after function, after update)</p>"; ?>
Now the output of this PHP example, is:
PHP Static Variable
Static variables are those variables that preserves their previous value during the execution of a function. To create a static variable, we need to use the static keyword before the variable to make it static.
PHP static keyword comes into picture when we needed to execute a function for multiple times preserving or using its previous values. As normally, variables gets deleted after the execution of a function. For example:
<?php function codes() { $x = 100; echo "<p>$x</p>"; $x++; } codes(); codes(); codes(); codes(); echo "<hr>"; function cracker() { static $y = 200; echo "<p>$y</p>"; $y++; } cracker(); cracker(); cracker(); cracker(); ?>
The output of above PHP example on static variable, is shown in the snapshot given below:
In above example, the variable $x inside the first function, that is codes() is defined as usual, therefore every time after executing the function, its value gets printed, and the variable gets deleted. But look at the variable $y defined in second function with static keyword, that makes the variable $y a static one. Therefore, it preserves its previous value, even after executing the function.
Here is another example, of static variable in PHP:
<?php function codescracker() { static $num = 2; echo "--Table of $num--<BR>"; for($i=1; $i<=10; $i++) echo "$num * $i = ", $num*$i, "<BR>"; $num++; } codescracker(); echo "<HR>"; codescracker(); ?>
The snapshot given below shows the sample output produced by above PHP example:
« Previous Tutorial Next Tutorial »