Php7 - PHP: global inside a function does not show a variable - Stack Overflow in Russian. Scope of PHP variables. Everything you wanted to know but were afraid to ask Print a global php variable outside a function

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.

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!

This tutorial covers the scope of PHP variables. Explains the difference between local and global scope, shows how to access global variables within a function, how to work with superglobals and create static variables.

When you start learning PHP and start working with functions and objects, variable scope is a bit confusing. Fortunately, PHP's rules in this regard are very easy to understand (compared to other programming languages).

What is scope?

The scope of variables is the context within which the variable was defined and where it can be accessed. PHP has two variable scopes:

  • Global- variables can be accessed anywhere in the script
  • Local- variables can only be accessed inside the function in which they were defined

The scope of a variable, and especially the local one, greatly simplifies code management. If all variables were global, then they could be changed anywhere in the script. This would lead to chaos and large scripts, since very often different parts of the script use variables with the same names. By limiting the scope to the local context, you define the boundaries of the code that can access a variable, which makes the code more robust, modular, and easier to debug.

Variables with global scope are called global, and variables with local scope are called local.

Here is an example of how global and local variables work.

"; ) sayHello(); echo "Value of \$globalName: "$globalName"
"; echo "\$localName value: "$localName"
"; ?>

Hi Harry! $globalName value: "Zoe" $localName value: ""

In this script we created two variables:

  • $globalName- This global variable
  • $localName- This local a variable that is created inside the sayHello() function.

After creating the variable and function, the script calls sayHello(), which prints "Hello Harry!" . The script then tries to output the values ​​of the two variables using the echo function. Here's what happens:

  • Because $globalName was created outside the function, it is available anywhere in the script, so "Zoe" is output.
  • $localName will only be available inside the sayHello() function. Since the echo expression is outside the function, PHP does not provide access to the local variable. Instead, PHP expects the code to create a new variable called $localName , which will have a default value of the empty string. that's why the second call to echo outputs the value "" for the $localName variable.

Accessing global variables inside a function

To access a global variable out of function Simply writing her name is enough. But to access a global variable inside a function, you must first declare the variable as global in the function using the global keyword:

Function myFunction() ( global $globalVariable; // Access the global variable $globalVariable )

If you don't do this, PHP assumes that you are creating or using a local variable.

Here is an example script that uses a global variable inside a function:

"; global $globalName; echo "Hello $globalName!
"; ) sayHello(); ?>

When executed, the script will output:

Hi Harry! Hello Zoya!

The sayHello() function uses the global keyword to declare the $globalName variable to be global. She can then access the variable and output its value (“Zoe”).

What are superglobals?

PHP has a special set of predefined global arrays that contain various information. Such arrays are called superglobals, since they are accessible from anywhere in the script, including internal function space, and do not need to be defined using the global keyword.

Here is a list of superglobals available in PHP version 5.3:

  • $GLOBALS - list of all global variables in the script (excluding superglobals)
  • $_GET - contains a list of all form fields submitted by the browser using a GET request
  • $_POST - contains a list of all form fields sent by the browser using a POST request
  • $_COOKIE - contains a list of all cookies sent by the browser
  • $_REQUEST - contains all key/value combinations that are contained in the $_GET, $_POST, $_COOKIE arrays
  • $_FILES - contains a list of all files downloaded by the browser
  • $_SESSION - allows you to store and use session variables for the current browser
  • $_SERVER - contains information about the server, such as the file name of the script being executed and the IP address of the browser.
  • $_ENV - contains a list of environment variables passed to PHP, such as CGI variables.
For example, you can use $_GET to get the values ​​of variables enclosed in a script's request URL string, and display them on the page:

If you run the above script using the URL http://www.example.com/script.php?yourName=Fred, it will output:

Hello Fred!

Warning! In a real script, such data transfer should never be used due to weak security. You should always validate or filter data.

The $GLOBALS superglobal is very convenient to use because it allows you to organize access to global variables in a function without the need for the global keyword. For example:

"; ) sayHello(); // Prints "Hello, Zoya!" ?>

Static variables: they are around somewhere

When you create a local variable inside a function, it only exists while the function is running. When the function completes, the local variable disappears. When the function is called again, a new local variable is created.

In most cases this works great. Thus, the functions are self-contained and always work the same every time they are called.

However, there are situations where it would be convenient to create a local variable that "remembers" its value between function calls. Such a variable is called static.

To create a static variable in a function, you must use the static keyword before the variable name and be sure to give it an initial value. For example:

Function myFunction() ( static $myVariable = 0; )

Let's consider a situation when it is convenient to use a static variable. Let's say you create a function that, when called, creates a widget and displays the number of widgets already created. You can try writing code like this using a local variable:


"; echo createWidget() . " we have already created.
"; echo createWidget() . " we have already created.>
"; ?>

But, since the $numWidgets variable is created every time the function is called, we will get the following result:

We create some widgets... We have already created 1. We have already created 1. We have already created 1.

But by using a static variable, we can store the value from one function call to another:

"; echo createWidget() . " we have already created.
"; echo createWidget() . " we have already created.
"; echo createWidget() . " >we have already created.
"; ?>

Now the script will produce the expected result:

We create some widgets... We have already created 1. We have already created 2. We have already created 3.

Although a static variable retains its value between function calls, it is only valid while the script is running. Once the script completes execution, all static variables are destroyed, as are local and global variables.

That's all! Please refer to your PHP documentation frequently.

The thing to note here is that the code element you presented should be considered as bad design and programming style, because it treats the included file as an instantly executable set of operations.

The most correct approach would be to put the set of operations as functions/classes with their own name in a file, include the file (without any return statement outside of the functions), and then call the function obviously with the required set of arguments.

So what's the problem?

Everything is extremely simple, you do it include inside a method method, which means the variables specified in the included file are initialized in the scope of the method method. Therefore, the variable $lang is not global and is limited by the visibility of the method, and you are accessing a global variable, so when using the modifier global it will be equal to null.

If you include in the global scope, then the lang variable will become public (global) and its use will become possible. This is easy to check; in the included file, before starting to define any variable, just write global $variable.

Example:

include "file1.php"; function include2() ( include "file2.php"; )
  • file1.php is defined in global scope.
  • file2.php is defined in the local scope of the include2 function.

The approach with global variables and such include is a crutch that will bring you problems in the future. Functions must be explicitly defined, have a unique name, and be executed on demand.

Why is the approach with global variables bad?

The point is that global variables are visible from everywhere, globally. This is convenient: there are no restrictions. On the other hand, it becomes completely impossible to track who changes the data. Uncontrolled changes are the first thing that usually comes to mind when asked why global variables are bad.

Let's say you have a function whose result depends on a global variable. You call it, call it, but after 10 minutes the function starts returning incorrect results. What's happened? After all, you are passing the same set of parameters to it as input? Hmm, someone changed the value of a global variable... Who could it be? Yes, anyone - after all, a global variable is available to everyone..

The best recipe for designing subroutines is: make the result of your function depend only on the arguments. This is an ideal to strive for.

Don't use global variables in your project unnecessarily, take advantage of all the features of local scope, passing parameters to function arguments, and the code will be easier to write, maintain, and test.

Do you know what is the best prefix for global variables?

Variables defined within a subroutine (user-defined function). They are only accessible within the function in which they are defined.

For PHP, all variables declared and used in a function are local to the function by default. That is, by default it is not possible to change the value of a global variable in the body of a function.

If in the body of a user-defined function you use a variable with a name identical to the name of a global variable (located outside the user-defined function), then this local variable will not have any relation to the global variable. In this situation, a local variable with a name identical to the name of the global variable will be created in the user-defined function, but this local variable will be available only within this user-defined function.

Let us explain this fact with a specific example:

$a = 100 ;

function function() (
$a = 70 ;
echo "

$a

" ;
}
function();
echo "

$a

" ;
?>

The script will print 70 first and then 100:

70
100

To get rid of this drawback, there is a special instruction in PHP global, allowing a user-defined function to work with global variables. Let's look at this principle using specific examples:

$a = 1 ;
$b = 2 ;

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

$b = $a + $b ;
}

Sum();
echo $b ;
?>

The above script will output " 3 ". After defining $a And $b inside the function like global all references to any of these variables will point to their global version. There is no limit to the number of global variables that can be handled by user-defined functions.

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:

Using $GLOBALS instead of global:

$a = 1 ;
$b = 2 ;

Function Sum()
{
$GLOBALS [ "b" ] = $GLOBALS [ "a" ] + $GLOBALS [ "b" ];
}

Sum();
echo $b ;
?>

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

function test_global()
{
// Most predefined variables are not
// "super" and to be available in the local area
// function visibility requires "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 available since PHP 4.1.0
echo $_POST ["name" ];
}
?>