Global variables in PHP. Php variable visibility scope variable visibility in functions

Last update: 11/1/2015

When using variables and functions, consider variable scope. The scope specifies the scope of action and accessibility of a given variable.

Local variables

Local variables are created inside a function. Such variables can only be accessed from within a given function. For example:

In this case, the get() function defines a local variable $result . And from the general context we cannot access it, that is, write $a = $result; This is not possible because the scope of the $result variable is limited by the get() function. Outside of this function, the $result variable does not exist.

The same applies to function parameters: outside the function, the $lowlimit and $highlimit parameters also do not exist.

As a rule, local variables store some intermediate results of calculations, as in the example above.

Static Variables

Static variables are similar to local variables. They differ in that after the function is completed, their value is saved. Each time the function is called, it uses the previously stored value. For example:

To indicate that a variable will be static, the keyword static is added to it. With three consecutive calls to getCounter(), the $counter variable will be incremented by one.

If the $counter variable were a regular non-static variable, then getCounter() would print 1 every time it was called.

Typically, static variables are used to create various counters, as in the example above.

Global Variables

Sometimes you want a variable to be available everywhere, globally. Such variables can store some data common to the entire program. To define global variables, use the global keyword:1

"; ) getGlobal(); echo $gvar; ?>

After calling the getGlobal() function, the $gvar variable can be accessed from any part of the program.

Variable scope is the context in which that variable is defined. Most PHP variables have a single scope. This single scope (also called the global scope) also covers included files:

In this example, the $a variable will also be available inside the included script - main.inc .

Local variables

A custom function definition specifies local scope for a variable, i.e. Any variable used inside a function is by default limited to the local scope of the function (available only within the function in which it is defined). How it works: To separate variables used in general code from variables used in functions, PHP provides separate storage for variables within each function. This division of storage space implies that the scope, that is, the area in which the value of a variable is available, is the function's local storage.

The example below clearly demonstrates that a variable declared outside a function does not change inside the function. While you shouldn’t try to understand how the function works, the main thing is that it has its own unique set of variables:

30 ?>

As a result of executing this fragment, the following will be displayed: 30.

Inside the birth() function, the variable $age is set to 1, but this is not the same variable that was defined in the global scope. Therefore, when the value of the $age variable is printed, the original value of 30 is printed. It is worth noting that local variables are created at the time the function is called and are deleted after the function finishes.

If you actually want to read or change the value of a global variable (as variables used in the global scope are called) rather than a local one within the birth() function, it must be declared global within the function definition.

The note: The adaptive version of the site is activated, which automatically adapts to the small size of your browser and hides some details of the site for ease of reading. Enjoy watching!

Hello dear blog readers Site on! In we learned that there is a function in PHP, we learned how to create our own functions, pass arguments to them and call them for execution. Continuing the topic of functions in PHP, it is necessary to emphasize the following things:

  • Inside the function, you can use any PHP code (cycles, conditions, any operations), including other functions (both built-in and custom);
  • The function name must begin with a Latin letter or an underscore, followed by any number of Latin letters, numbers or underscores;
  • All functions have global scope, which means that any function can be called anywhere, even if that function is defined inside another;
  • PHP does not support function overloading; there is also no possibility to redefine (change, add) or delete a created function;
  • Functions do not have to be defined before they are used. That is, if you first call a function, and only then describe it in the code below, this will not affect the performance and will not cause errors.

Conditional Functions

We can create (define, describe) a function depending on the condition. For example:

//called the function sayHi, it can be called anywhere /*the sayGoodbye function cannot be called here, since we have not yet checked the condition and have not gone inside the if construct*/ if($apply)( function sayGoodbye())( echo "Bye everyone!
"; } } /*now we can call sayGoodbye*/
"; }

Result:

And take a look at this example:

/*and this is what will happen if you call sayGoodbye here*/ sayGoodbye(); if($apply)( function sayGoodbye())( echo "Bye everyone!
"; ) ) function sayHi())( echo "Hello everyone!
"; }

Result:

In fact, as much as I’ve been working, I’ve never seen anything like this anywhere, but you need to keep in mind all the possibilities of the language.

Nested functions

A nested function is a function declared inside another function. Example:

/*You cannot call sayGoodbye here, since it will appear only after calling the sayHi function*/ sayHi(); /*call the function sayHi, it can be called anywhere*/ /*Now we can call sayGoodbye*/ sayGoodbye(); function sayHi())( echo "Hello everyone!
"; function sayGoodbye())( echo "Bye everyone!
"; } }

Again, on the first traversal, the PHP interpreter marks itself that it has found a description of the sayHi function, but does not go inside its body, it only sees the name, and since the interpreter does not go inside the body of sayHi, then it has no idea what we are defining inside another function – sayGoodbye.

Then the code starts executing, we call sayHi, the PHP interpreter has to go into the body of the sayHi function to execute it and there it accidentally finds the description of another function - sayGoodbye, after which sayGoodbye can be called anywhere, as many times as you like.

But it’s worth paying attention to a very subtle point in the situation above: the sayHi function becomes one-time, because if we call it again, PHP will again come across the definition of the sayGoodbye function, and in PHP you can’t do this - you can’t override functions. I wrote about this and how to deal with it in a previous article.

In PHP, the techniques described above are used very rarely; they can be seen more often, for example, in JavaScript.

Variable Scope

There are exactly two scopes in PHP: global And local. Each programming language structures scopes differently. For example, in C++, even loops have their own (local) scope. In PHP, by the way, this is a global scope. But today we are talking about functions.

Functions in PHP have their own internal scope (local), that is, all variables inside a function are visible only within this very function.

So, once again: everything outside the functions is the global scope, everything inside the functions is the local scope. Example:

Dear experts, attention, question! What will the last instruction output? echo $name; ?

As you saw for yourself, we had 2 variables $name, one inside the function (local scope), the other just in the code (global scope), the last assignment to a variable $name was $name = "Rud Sergey"; But since it was inside the function, it stayed there. In the global scope, the last assignment was $name = "Andrey"; which is what we actually see as a result.

That is, two identical variables, but in different scopes they do not intersect and do not affect each other.

Let me illustrate the scope in the figure:

During the first traversal, the interpreter briefly scans the global scope, remembers what variables and functions there are, but does not execute the code.

Accessing global variables from local scope

But what if we still need to access the same $name variable from the global scope from a function, and not just access it, but change it? There are 3 main options for this. The first one is using the keyword global:

"; global $name; /*from now on we mean the global variable $name*/$name = "Rud Sergey"; ) $name = "Andrey"; sayHi($name); echo $name; // ?

Result:

But this method has a disadvantage, since we accessed the global variable $name we lost (overwrote) a local variable $name.

Second way is to use PHP superglobal array. PHP itself automatically places every variable that we created in the global scope into this array. Example:

$name = "Andrey"; //Same as$GLOBALS["name"] = "Andrey";

Hence:

"; $GLOBALS["name"] = "Rud Sergey"; ) $name = "Andrey"; sayHi($name); echo $name; // ?

The result is the same as using the keyword global:

Only this time we did not rewrite the local variable, that is, the variable $name inside the function remains the same and is equal "Andrey", but not "Rud Sergey".

Passing arguments by reference

Third way– this is the transfer of address ( links) of a variable, not its value. Links in PHP are not very successful, unlike other programming languages. However, I will tell you the only correct option for passing an argument by reference to a function, which is normally supported in PHP 5.3 and higher. There are other ways to work with links, but they worked in PHP 5.2 and lower, as a result, the PHP developers themselves decided to abandon them, so we won’t talk about them.

So, the CORRECT passing of an argument by reference in PHP 5.3 and higher is done as follows:

Function sayHi(& $name)(

In the function description itself, we added an ampersand icon (&) - this icon means that we do not accept the value of the variable, but a link (address) to this value in memory. References in PHP allow you to create two variables pointing to the same value. This means that when one of these variables changes, both change, since they refer to the same value in memory.

And in the end we have:

//accept not a value, but a reference to the value echo "Hello, ".$name."!
"; $name = "Rud Sergey"; ) $name = "Andrey"; sayHi($name); echo $name; // ?

Result:

Static Variables

Imagine the following situation: we need to count how many times we said hello in total. Here's what we're trying to do:

"; $c++; // increase the counter by 1


Result:

Variable $c does not remember its meaning, it is created anew every time. We need to make our local variable $c remembered its value after executing the function, for this they use a keyword static:

// counter, made static echo "Hello, ".$name."!
"; $c++; // increase the counter by 1 echo "Just said hello " . $c . " once.


"; ) sayHi("Rud Sergey"); sayHi("Andrey"); sayHi("Dmitry");

Result:

Returning values

Functions have such a convenient thing as returning values. This is when a function, instead of printing something to the screen, puts everything into a variable and gives that variable to us. And we are already deciding what to do with it. For example, let's take this function, it squares a number:

Result:

Let's make it so that instead of displaying it on the screen, it returns the execution result. To do this, use the return keyword:

Result:

Now we can use this in various ways:

//outputs the result echo "
"; $num = getSquare(5); echo $num;

Result:

Please note that the keyword return does not just return a value, but completely interrupts the function, that is, all the code that is below the keyword return will never be fulfilled. In other words, return for functions also works like break for loops:

echo "PHP will never reach me:(";) echo getSquare(5); //outputs the result echo "
"; $num = getSquare(5); // assigned the result to a variable echo $num; // display the variable on the screen

Result:

That is return– this is also an exit from the function. It can be used without a return value, just for the sake of output.

Recursive function

A recursive function is a function that calls itself. Recursion is not used often and is considered a resource-intensive (slow) operation. But it happens that using recursion is the most obvious and simple option. Example:

"; if($number< 20){ // so that the recursion does not become endless countPlease(++$number); // the countPlease function called itself) ) countPlease(1);

Result:

If you know how to do without recursion, then it is better to do so.

Strong typing in PHP (type refinement)

PHP takes small steps towards strong typing, so we can specify in advance what type a function should take (this is called type-hint):

Result:

Catchable fatal error: Argument 1 passed to countPlease() must be an array, integer given, called in /home/index.php on line 7 and defined in /home/index.php on line 3

The error tells us that the function expects to receive an array, but instead we are passing it a number. Unfortunately, for now we can only specify the type for (array), and with PHP 5.4 we also added such an option as callable:

Callable checks whether the passed value can be called as a function. Callable can be either the name of a function specified by a string variable, or an object and the name of the method being called. But we will talk about objects and methods later (this is a section of object-oriented programming), but you are already familiar with functions. I can’t show you the result of the work, since I currently have PHP 5.3, but it would be:

Called the getEcho function

Using Variable Length Arguments

And finally, one more very rarely used nuance. Imagine a situation: we pass arguments to a function, although we did not describe them in the function, for example:

Result:

As you can see, there are no errors, but our passed arguments are not used anywhere. But this does not mean that they are gone - they were still passed into the function and we can use them; there are built-in PHP functions for this:

func_num_args()- Returns the number of arguments passed to the function
func_get_arg(sequence number)- Returns an element from a list of arguments
func_get_args()- Returns an array containing the function arguments

"; echo func_get_arg(0) ; ) $age = 22; getEcho("Rud Sergey", $age);

Result:

Conclusion

Today's article is the final one on the topic of functions in PHP. Now you can be confident in the completeness of your knowledge regarding this topic and can confidently use the functions for your needs.

If someone has a desire to get better at it, but has no idea how to do it, the best way would be to write ready-made (built-in) PHP functions, for example, you can write your own count() function or any other.

Thank you all for your attention and see you again! If something is not clear, feel free to ask your questions in the comments!

The scope of a variable is the context in which the variable is defined. In most cases, all PHP variables have only one scope. This single scope also covers included and required files. For example:

$a = 1 ;
include "b.inc" ;
?>

Here the $a variable will be available inside the included b.inc script. However, the definition (body) of a user-defined function specifies the local scope of that function. Any variable used within a function is by default limited to the function's local scope. For example:

$a = 1 ; /* global scope */

Function test()
{
echo $a ; /* reference to local scope variable */
}

Test();
?>

This script will not generate any output because the echo statement points to a local version of the variable $a and it has not been assigned a value within that scope. You may have noticed that this is a little different from C in that global variables in C are automatically available to functions unless they have been overwritten by a local definition. This can cause some problems as people may accidentally change the global variable. In PHP, if a global variable is to be used within a function, it must be declared global within the function definition.

Keyword global

First a usage example global:

Example #1 Usage global

$a = 1 ;
$b = 2 ;

function Sum()
{
global $a, $b;

$b = $a + $b ;
}

Sum();
echo $b ;
?>

The above script will output 3 . Once $a and $b are defined as global inside a function, all references to any of these variables will point to their global version. There is no limit to the number of global variables that a function can handle.

The second way to access global scope variables is to use a special PHP-defined array, $GLOBALS . The previous example could be rewritten like this:

$GLOBALS is an associative array whose key is the name and value is the contents of the global variable. Note that $GLOBALS exists in any scope, this is because $GLOBALS is superglobal. Below is an example demonstrating the capabilities of superglobals:

Example #3 Superglobals and scope

function test_global()
{
// Most predefined variables are not
// "super" and to be available in the local area
// visibility, functions require "global" to be specified.
global $HTTP_POST_VARS ;

Echo $HTTP_POST_VARS["name"];

// Superglobals are available in any scope
// visibility and do not require "global" to be specified.
// Superglobals are available since PHP 4.1.0, and
// use of HTTP_POST_VARS is deprecated.
echo $_POST ["name" ];
}
?>

Comment:

Keyword usage global outside the function is not an error. It can be used in a file that is included inside a function.

Using static ( static) variables

Another important feature of variable scope is static variable. A static variable exists only in the local scope of a function, but does not lose its value when program execution leaves that scope. Consider the following example:

Example #4 Demonstrating the need for static variables

function test()
{
$a = 0 ;
echo $a ;
$a++;
}
?>

This function is pretty useless because every time it is called it sets $a to 0 and outputs 0 . The increment of the $a ++ variable does not play a role here, since the $a variable disappears when the function exits. To write a useful counting function that doesn't lose the current counter value, the variable $a is declared static:

Example #5 Example of using static variables

function test()
{
static $a = 0 ;
echo $a ;
$a++;
}
?>

Now $a will be initialized only on the first function call, and each function call test() will print the value of $a and increment it.

Static variables also make it possible to work with recursive functions. A recursive function is one that calls itself. When writing a recursive function, you need to be careful, since there is a possibility of making the recursion infinite. You must ensure that there is an adequate way to terminate the recursion. The following simple function counts up to 10 recursively, using the static variable $count to determine when to stop:

Comment:

Static variables can be declared as shown in the previous example. Attempting to assign values ​​to these variables that are the result of expressions will cause a processing error.

Example #7 Declaring static variables

function foo ()(
static $int = 0 ; // right
static $int = 1 + 2 ; // incorrect (since it's an expression)
static $int = sqrt(121); // incorrect (since this is also an expression)

$int++;
echo $int ;
}
?>

Comment:

Static declarations are evaluated during script compilation.

Links with global ( global) and static ( static) variables

Zend Engine 1, which powers PHP 4, treats static and global variable modifiers as references. For example, a real global variable embedded in the scope of a function by specifying the keyword global, in effect creates a reference to a global variable. This can lead to unexpected behavior, as shown in the following example:

function test_global_ref() (
global $obj ;
$obj = &new stdclass ;
}

function test_global_noref() (
global $obj ;
$obj = new stdclass ;
}

test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);
?>

The result of running this example: get_instance_noref () (
static $obj ;

Echo "Static object: ";
var_dump($obj);
if (!isset($obj )) (
// Assign an object to a static variable
$obj = new stdclass ;
}
$obj -> property++;
return $obj ;
}

$obj1 = get_instance_ref();
$still_obj1 = get_instance_ref();
echo "\n" ;
$obj2 = get_instance_noref();
$still_obj2 = get_instance_noref();
?>

The result of running this example:

Static object: NULL
Static object: NULL

Static object: NULL
Static object: object(stdClass)(1) (
["property"]=>
int(1)
}

This example demonstrates that when you assign a reference to a static variable, it does not memorable when you call the function &get_instance_ref() a second time.

To create a full-fledged website with a wide range of functions, you need to know a lot. However, PHP can give a site real uniqueness. The global variable is not often used in this programming language, but sometimes it is very useful to know how it works.


In this article we will study exactly what a global variable is and how it works.

Global variable: scope

The context within which a variable is defined is called its scope. Typically, variables have only one scope. When global variables in PHP are loaded from other files, they can be required or included. They are by default limited to the local scope of the function. How can you make a variable visible to files beyond its boundaries and also be able to use it? This is exactly why PHP provides a global variable. The key word here is “global”. How to declare a global variable in PHP? To achieve this goal, the word "global" must be used. It must be placed immediately before the variable that you want to make global. It looks something like this: global “Variable”. After implementing instructions of this kind, absolutely any file will be able to work with data.

If there are references to this variable somewhere, the program will pay attention to the global version. Why is such strange wording used? The thing is that at the same time, local versions can also exist. But they will be more accessible exclusively in the files in which they are declared. For the rest, global PHP class variables will apply. Here you need to act very carefully and carefully. To prevent any doubts, let's give a simple example of how they might look: global a. If one file has access to multiple variables, this could cause a conflict. But it’s impossible to say for sure here whether a global or local variable will be read, or whether an error will occur. If you write it inside a function, no problems should arise. Using a variable outside the boundaries of a function will be problematic. Therefore, you need to very carefully monitor the structure of the code and make sure that there are no prerequisites for a conflict anywhere.

Global Variables: Another Notation
Are there other ways to set global variables? Yes, and not alone. Let's look at $GLOBALS first. It is an associative array in which the key is the name. The contents of the global variable are used as the value. It is worth noting that after declaration, this array exists in any scope. This gives grounds to consider it super-global. It looks like this: $GLOBALS ['Variable'].

Superglobals
In any programming language, there are names that are reserved for individual functions. It’s simply not possible to create global variables of the same name in PHP. This programming language has its own characteristics. For example, it is especially important that predefined variables do not have the prefix “super”. This means they are not available in all locations. How can this situation be corrected? To make a predefined variable available on some local network, you need to declare it like this: global "variable". This has already been mentioned earlier. However, this is not entirely true. Let's look at a real example:
Global $HTTP_POST_VARS; echo $HTTP_POST_VARS ['name'].
Do you feel the difference? It is worth keeping in mind that in PHP a global variable must be used within a function. It may also be located in a file that is included in it.

Security and Links
As you can see for yourself, creating a global variable in PHP is not a problem. But are there any specifics regarding links? When using global variables, some unexpected behavior is possible. But before studying this issue in more detail, it is necessary to turn to the background. The register_globals directive was changed from enabled to disabled by default in version 4.2. For many users, this is completely unimportant, and in vain, because the safety of the product being developed directly depends on it. If you need to make a global variable, then the PHP directive will not directly affect this setting. However, incorrect use can become a security risk. So, for example, if register_globals is in the enabled state, then various necessary variables will be initialized before the code is executed. Therefore, they decided to turn it off. Why does a global variable owe much of its state to a given directive? The problem is that when enabled, developers were not always able to answer the question of where it came from, but on the other hand, this greatly facilitated the process of writing code. At the same time, such an organization created a certain threat to security. To avoid data mixing and errors, the directive was disabled. Now let's look at an example of unsafe code. We will also look at how you can detect cases when the declaration of a PHP global variable is accompanied by an attempt to replace information. This is required in order to create stable working sites that cannot be hacked by the first user who comes across them.

Dangerous codes
Let's set the variable to true for those users who are authorized:
If (authenticate_user()) ($authoriza=true;) if ($authorize) ( include “/highly/sensitive/data.php”;). A variable in this state can be set automatically. Considering that the data can simply be replaced, and the source of its origin is not established, then virtually any user can pass such a check and impersonate anyone. An attacker, if desired, can disrupt the logic of the entire script. If you change the value of the directive, the code will work correctly. This is exactly what we need to do. However, initializing variables is not only a good practice among programmers, it also guarantees the stability of the script.

Reliable option
To achieve this goal, you can try to disable the directive, or write more complex code, for example, like this: if (isset($_SESSION ['username'])) (echo “Hello” ($_SESSION ['username'])”;) else (echo “Hello Guest”; echo “Welcome!”;). In this case, it will be difficult to make a substitution. However, it is possible. To do this, you need to take care of the availability of rapid response tools in advance. If you need to include global variables in PHP, you can use the following tool: if you know exactly in which range the value will be received, then you can write it in such a way that the script checks this fact by comparison. This, of course, also cannot guarantee 100% protection against value substitution. However, going through the possible options will significantly complicate the operation.

How to detect a spoofing attempt?
Now let's check if you understood everything previously written correctly. You will need to declare global variables in a function yourself. This is a kind of homework. First, here's the code:

Let's give some explanations. The C_COOKIE variable is taken from a reliable source. To ensure that its result is as expected, the variable's value is checked. If problems arise, the administrator receives a notification. If nothing happens, no action will be taken.