Local variables in php functions

PHP Variables Scope

In PHP, variables can be declared anywhere in the script.

The scope of a variable is the part of the script where the variable can be referenced/used.

PHP has three different variable scopes:

Global and Local Scope

A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:

Example

Variable with global scope:

function myTest() // using x inside this function will generate an error
echo «

Variable x inside function is: $x

«;
>
myTest();

echo «

Variable x outside function is: $x

«;
?>

A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:

Example

Variable with local scope:

function myTest() $x = 5; // local scope
echo «

Variable x inside function is: $x

«;
>
myTest();

// using x outside the function will generate an error
echo «

Variable x outside function is: $x

«;
?>

You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared.

PHP The global Keyword

The global keyword is used to access a global variable from within a function.

To do this, use the global keyword before the variables (inside the function):

Example

function myTest() global $x, $y;
$y = $x + $y;
>

myTest();
echo $y; // outputs 15
?>

PHP also stores all global variables in an array called $GLOBALS[index] . The index holds the name of the variable. This array is also accessible from within functions and can be used to update global variables directly.

The example above can be rewritten like this:

Example

function myTest() $GLOBALS[‘y’] = $GLOBALS[‘x’] + $GLOBALS[‘y’];
>

myTest();
echo $y; // outputs 15
?>

PHP The static Keyword

Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job.

To do this, use the static keyword when you first declare the variable:

Example

Then, each time the function is called, that variable will still have the information it contained from the last time the function was called.

Note: The variable is still local to the function.

Источник

PHP Variable Scopes

Summary: in this tutorial, you’ll learn about PHP variable scopes, which specify the part of code that can access a variable.

Introduction to PHP variable scopes

The scope of a variable determines which part of the code can access it. The locations where the variable can be accessible determine the scope of the variable.

In PHP, variables have four types of scopes:

Local variables

When you define a variable inside a function, you can only access that variable within the function. And it’s said that the variable is local to the function.

The following example defines the say() function that displays the ‘Hi’ message:

 function say() < $message = 'Hi'; echo $message; >Code language: PHP (php)

Inside the say() function, we define the $message variable. The $message variable is a local variable. And you cannot access it from the outside of the say() function.

Also, the $message variable only exists during the execution of the say() function. Once the say() function ends, the $mesage variable won’t exist anymore.

Global variables

When you declare a variable outside of a function, the variable is global. It means that you can access the variable anywhere within the script except inside a function. For example:

 $message = 'Hello'; function say() < $message = 'Hi'; echo $message; > echo $message; // HelloCode language: PHP (php)

In this script, we have two variables with the same name $message .

The first variable is the global variable because we define it outside of a function. The $message variable that we define inside the function is the local variable. Even though these variables have the same name, they’re two different variables.

PHP allows you to access a global variable within a function by using the global keyword. For example:

 $message = 'Hello'; function say() < global $message; echo $message; // Hello > say();Code language: PHP (php)
  • First, define a global variable called $message .
  • Second, reference the global variable $message inside the say() function.

It’s important to note that it’s not a good practice to use global variables.

Superglobal variables

PHP has a list of built-in variables, which are known as superglobal variables. The superglobal variables provide information about the PHP script’s environment.

The superglobal variables are always available in all parts of the script. The following table shows the list of PHP superglobal variables:

Superglobal Variables Meaning
$GLOBALS Returns an array that contains global variables. The variable names are used to select which part of the array to access.
$_SERVER Returns data about the webserver environment.
$_GET Return data from GET requests.
$_POST Return data from POST requests.
$_COOKIE Return data from HTTP cookies
$_FILES Return data from POST file uploads.
$_ENV Return information about the script’s environment.
$_REQUEST Return data from the HTTP request
$_SESSION Return variables registered in a session

Static variables

A static variable retains its value between function calls. Also, a static variable is only accessible inside the function. To define a static variable, you use the static keyword. For example:

 function get_counter() < static $counter = 1; return $counter++; > echo get_counter() . '
'
; // 1 echo get_counter() . '
'
; // 2 echo get_counter() . '
'
; // 3
Code language: PHP (php)
1 2 3Code language: plaintext (plaintext)
  • First, define the get_counter() function with a static variable named $counter .
  • Second, call the set_counter() function three times. As you notice that the value of the $counter variable is increased by one after each function call.

Function parameters

Function parameters are local to the function. Therefore, function parameters can only be accessible inside the function. For example:

 function sum($items) < $total = 0; foreach($items as $item) < $total += $item; >return $total; > // $items cannot be accessible here echo sum([10,20,30]);Code language: PHP (php)

In this example, the $items is the parameter of the sum() function. It can only be accessible within the sum() function.

Summary

Источник

Local Variable in PHP

Local Variable in PHP

Local variables are those variables that are declared inside the function of a Php program and have their scope inside that function only. Local variables have no scope outside the function (variable cannot be referenced outside the function), so cannot be used outside its scope in the program. If any other variable with the same name is used in a program outside a function(a global variable), it is considered differently and has its own identity, and considered as a completely different variable. Local variables follow the same characteristics of a normal variable, i.e. starting with the ‘$’ sign and the variable name starting with (a-z) or underscore ( _ ) sign.

Web development, programming languages, Software testing & others

Syntax

If we talk about the syntax, there is no such syntax of using the local variable in an oho program. The program needs to define the variable inside a function and use it there only.

How does the local variable work in Php?

There are basically 3 broad categories of variables in Php, i.e. Local Variable, Global Variable, and Static Variables. All the variables have the difference in the scope and the way they are defined in the program. Elaborating the local variables in this article, below given are some of the important points which the programmer needs to understand in order to have a clear vision of a local variable in Php:

Local variables are declared and used inside the function only. Local variables in Php have the Local scope (cannot be used outside the function). If a global variable exists with the same name as the local variable in the program, they have nothing to do with each other. They both are completely different from each other.

When the local variable is called inside the function, its value will get printed on the console. Local variables, if printed or used in any way outside the function in a php program, give an error to the user. Like the normal variable in Php, the local variable also starts with the ‘$’ sign.

Examples

It is important to perform and try things programmatically in order to have a better understanding. Below given are some of the examples of the Php program showing the usage of the local variables:

Example #1

Program to print the value of local variable outside the function

   Hello the value of local variable inside the function is : $name

"; > //calling the function myLocal(); // printing the value of local variable outside the function, gives an error echo "

Value of local variable outside the function is : $name

"; ?>

local vaiable in php 1

Explanation:

In the above example, ‘myLocal’ is the function in Php and ‘name’ is the local variable of the function ‘myLocal’ having the value ‘Rajesh’. Function myLocal is called. When the value of the local variable ‘name’ is printed on the console inside the function, ‘Rajesh’ is printed and on printing the value of that variable outside the function, nothing is displayed as the variable ‘name’ has the local scope.

Example #2

Program having the value of both local and Global variables with the same name and different values.

   Hello the value of local variable inside the function is : $name

"; > //calling the function myLocal(); // printing the value of variable outside the function, will consider the global function echo "

Value of variable outside the function is : $name

"; ?>

local vaiable in php 2

Explanation:

In the above example, myLocal() is the name of the function having the local variable ‘name’ with the value ‘Rajesh’. There is a variable ‘name’ with the value ‘Ankita’ defined at the starting of the code outside the function ‘myLocal’. When the value of the variable ‘name’ is printed on the console inside the function, ‘Rajesh’ is printed whereas when it is printed outside the function, ‘Ankita’ is printed as both the variables ‘name’, although having the same name but are completely different from each other. They have nothing to do with each other.

Example #3

Program having the 2 functions with the same name of variables in both the functions.

    Result of the above addition : $addition

"; > //function subtraction with the 2 local variables 'value1' and 'value2' function subtraction() < $value1 =99; $value2 =9; $subtraction =$value1 - $value2; echo "

Result of the above subtraction : $subtraction

"; > //calling the above 2 functions addition(); subtraction(); // printing the values of the local variables outside the function echo "

Result of the above addition outside function : $addition

"; echo "

Result of the above subtraction outside function : $subtraction

"; ?>

Example 3

Explanation:

In the above example, 2 functions are used,i.e. addition and subtraction respectively. Both the functions have the local variables ‘value1’ and ‘value2’. Both the variables have their scope inside their own functions only. Addition and Subtraction are performed inside the functions and the result is stored in their local variables ‘addition’ and ‘subtraction’ respectively. When the values of these local variables are printed inside their respective functions, the results are displayed on the console. When the values of these variables are printed outside the functions, nothing is displayed to the user.

Conclusion

Above description completely explains what are local variables in Php and how they are used in a Php program in their local scope only. Before proceeding for the advanced concepts, it is very important for a programmer to understand the basic thing clearly and use them in a program for clear and in-depth knowledge of the concepts.

This is a guide to Local Variable in PHP. Here we discuss the definition, syntax, and working of local variables in Php along with examples and code implementation. You may also have a look at the following articles to learn more –

25+ Hours of HD Videos
5 Courses
6 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

92+ Hours of HD Videos
22 Courses
2 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

83+ Hours of HD Videos
16 Courses
1 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

PHP Course Bundle — 8 Courses in 1 | 3 Mock Tests
43+ Hours of HD Videos
8 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

Источник

Читайте также:  Своих index php do lastcomments
Оцените статью