Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Global Variables and Global Scope
2.1.
Declaring Global Variables
2.2.
Accessing and Modifying Global Variables
3.
Local Variables and Local Scope
3.1.
Declaring Local Variables
3.2.
Accessing and Modifying Local Variables
4.
Static Variables and Associated Scope
4.1.
Declaring Static Variables
4.2.
Accessing and Modifying Static Variables
5.
Super Global Variables
5.1.
Accessing Super Global Variables
5.2.
Modifying Super Global Variables
6.
Frequently Asked Questions
6.1.
What is a global variable in PHP, and how do you declare it?
6.2.
Can local variables in PHP be accessed outside of their function?
6.3.
What is the scope of variables in PHP?
6.4.
What are static variables in PHP?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

PHP Variables Scope

Author Sanchit Kumar
0 upvote

Introduction

Be it any programming language; variables are the heart of code. And to understand the heart, we need to know how we can use it with the help of scopes. Scope refers to the part of the program where a variable can be accessed and used.

PHP Variables Scope

With this article on the PHP variables scope, we will explore the various types of scopes and play with variables within each scope, along with examples, code, and explanations.

Global Variables and Global Scope

In PHP, the global scope refers to variables accessible from anywhere within the script, including inside functions and classes.

Declaring Global Variables

Declaring a variable outside of all functions makes that variable global by default.


Example

<?php
$name;

function function1() {
	// … statements
}

function function2() {
	// … statements
}

?>
You can also try this code with Online PHP Compiler
Run Code


Explanation

We declared a global variable $name in our code.

Accessing and Modifying Global Variables

We can access global variables anywhere in our code, including inside functions and classes. Since global variables are available globally, we can use the variable name wherever needed. Also, we can modify global variables by directly assigning a new value to them.


Example

<?php
$number = 1;

function function1() {
	global $number;
	$number++;
}
function function2() {
	global $number;
	$number++;
}

function1();
function2();
echo $number;
?>
You can also try this code with Online PHP Compiler
Run Code


Output

3


Explanation

The above code has a global variable $number having value 1. Inside the function1() function, we have used the global keyword to access the global variable $number and incremented it. We did the same thing in the function2() function also. Without the global keyword, the $number would be treated as a local variable within each function, and any changes to it would not affect the global variable. Then we called function1() and function2() and output the value of $number using echo, and we got 3 as output.

Local Variables and Local Scope

In PHP, the local scope refers to variables declared inside a function or a code block, and we can only access them within that specific context.

Declaring Local Variables

To declare a local variable, we simply write the variable's name inside a function or a code block.


Example

<?php
function functionName() {
	$name = "Eloisa";
	echo "Hello, ". $name;
}

functionName();
?>
You can also try this code with Online PHP Compiler
Run Code


Output

Hello, Eloisa


Explanation

In our code above, we have a function functionName() where we declare a local variable $name and assign it the value "Eloisa". Then we concatenated the variable $name with the "Hello, " string and output the result. When we call functionName(), it prints "Hello, Eloisa".

Accessing and Modifying Local Variables

We can only access local variables from within the same function or code block where they are declared. Attempting to access them from outside their scope will result in an error. Local variables can be modified by reassigning new values to them within the same scope.


Example

<?php
function increment() {
	$counter = 0;
	$counter++;
	echo $counter;
}

increment();
?>
You can also try this code with Online PHP Compiler
Run Code


Output

1


Explanation

In our code above, we have a function increment() where we declare a local variable $counter and initialise it to 0. We then increment the value of the $counter by 1 and output it. When we call the increment() function, it prints 1.

Static Variables and Associated Scope

Static variables are variables that retain their value even after the function or code block where they are declared has finished executing. They are helpful when we need to persist data across multiple function calls.

Note - The term "static scope" is frequently used informally to refer to the scope in which static variables are defined. Still, it has no official definition or particular behaviour in PHP other than the scoping rules of static variables.

Declaring Static Variables

We use the static keyword before the variable name to declare a static variable.


Example

<?php
function increment() {
	static $counter = 0;
	$counter++;
	echo $counter;
}

increment();
increment();
?>
You can also try this code with Online PHP Compiler
Run Code


Output

12


Explanation

In our code above, we have a function increment() where we declare a static variable $counter using the static keyword. We initialise it to 0. Inside the function, we increment the value of the $counter by 1 and output it. When we call the increment() function multiple times, it keeps track of the value of the $counter and increments it accordingly.

Accessing and Modifying Static Variables

Static variables can be accessed and used within the same function or code block where they are declared, similar to local variables. Static variables can be modified within the same function or code block where they are declared by reassigning new values to them. The updated value will be retained across multiple calls to the function.

Example

<?php
function increment() {
	static $counter = 0;
	$counter++;
	echo $counter;
}

increment();
// echo $counter;
?>
You can also try this code with Online PHP Compiler
Run Code


Output

1


If we uncomment the "// echo $counter;" we will get an error.

Error: Undefined variable

 

Explanation

In our code above, we have a function increment() with a static variable $counter initialised to 0. Inside the function, we increment the value of the $counter by 1 and output it. When we call the increment() function, it prints 1. However, when we try to access the $counter variable outside the function, we get an error because it is not defined in the global scope.

Super Global Variables

Super global variables are predefined variables in PHP that are available in all scopes throughout the script. They are accessible from any function, class, or file without using the global keyword.

Some common examples of super global variables in PHP are:

  • $_GET: Contains the query string parameters from a GET request.
     
  • $_POST: Contains the form data from a POST request.
     
  • $_SESSION: Contains session variables.
     
  • $_COOKIE: Contains cookie variables.
     
  • $_SERVER: Contains server and execution environment information.
     

Accessing Super Global Variables

Super global variables can be accessed directly without any additional declaration or keyword.


Example using $_GET:

<?php
// URL: http://something.domain/?name=Eloisa
echo $_GET['name'];
?>
You can also try this code with Online PHP Compiler
Run Code


Output

Eloisa

 

Explanation

We accessed the $_GET super global variable in the code containing the query string parameters from a GET request. We accessed the value of the "name" parameter by using the key 'name' within the $_GET array. In this example, if the URL is "http://something.domain/?name=Eloisa", it will output "Eloisa".

Modifying Super Global Variables

We can modify the super global variables by assigning new values to their respective keys. However, modifying certain super global variables, such as $_SERVER or $_POST, is generally not recommended as they contain important system or user data.


Example using $_SESSION:

<?php
session_start();
$_SESSION['name'] = 'Eloisa';
?>
You can also try this code with Online PHP Compiler
Run Code


Explanation

We started/resumed a session using session_start(). After that, we assigned $_SESSION super global variable the value 'Eloisa' to the 'name' key. This allows us to store and retrieve session-specific data. However, validating user input is essential before using super global variables to avoid security vulnerabilities.

Frequently Asked Questions

What is a global variable in PHP, and how do you declare it?

A global variable in PHP is a variable that we can access and modify from anywhere in the script. We use the global keyword to declare a global variable and write the variable's name inside or outside any function or class.

Can local variables in PHP be accessed outside of their function?

No, local variables in PHP have a limited scope. We can only access them within the function where they are defined.

What is the scope of variables in PHP?

In PHP, the different program parts where the variable is accessible is the scope of that variable.

What are static variables in PHP?

Static variables in PHP are local variables that retain their values between function calls. They are declared using the static keyword.

Conclusion

In this article, we explored the PHP variables scope. We covered global and local variables, static variables, and super-global variables. By understanding the scope of variables, you can effectively manage data in your PHP applications and create efficient code. Alright! So now that you have learnt about PHP variables scope, you can also refer to other similar articles.


You may refer to our Guided Path on Code Studios for enhancing your skill set on DSACompetitive ProgrammingSystem Design, etc. Check out essential interview questions, practice our available mock tests, look at the interview bundle for interview preparations, and so much more!

Happy Learning, Ninja!

Live masterclass