Not passing global variables to php. PHP: global inside function doesn't show variable - Stack Overflow

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

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 theme of functions in PHP, the following things need to be emphasized:

  • Inside the function, you can use any PHP code (loops, conditions, any operations), including other functions (both built-in and your own);
  • The function name must begin with a Latin letter or underscore, followed by any number of Latin letters, numbers, or underscores;
  • All functions have a global scope, which means that any function can be called anywhere, even if that function is defined within another;
  • PHP does not support function overloading, and there is no way to override (change, add) or delete a created function;
  • Functions do not have to be defined before they are used. That is, if you first call the function, and only then - describe it below in the code, then 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:

//call the sayHi function, 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 happens 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 work, I have never seen 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 can't call sayGoodbye here, as it will only appear after calling the sayHi function*/ sayHi(); /*call the sayHi function, 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 notes to itself that it has found the 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 sayHi body, it has no idea what we are defining inside one more function - sayGoodbye.

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

But it is 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 stumble upon the definition of the sayGoodbye function, and in PHP this cannot be done - you cannot redefine 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

PHP has exactly two scopes: global and local. Scopes are organized differently in every programming language. For example, in C++, even loops have their own (local) scope. In PHP, by the way, this is the global scope. But today we are talking about functions.

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

So, once again: everything that is outside the functions is the global scope, everything that is 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 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"; what we actually see as a result.

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

Let me illustrate scopes in the figure:

During the first traversal, the interpreter skims the global scope, remembers what variables and functions 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 the function, and not just access it, but change it? There are 3 main options for this. The first one is the use of 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 minus, since we turned to the global variable $name we have lost (overwritten) a local variable $name.

Second way is to use PHP superglobal array. Into this array, PHP itself automatically puts every variable that we have created in the global scope. Example:

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

Consequently:

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

The result is the same as when using the keyword global:

Only this time we didn't overwrite the local variable, i.e. the variable $name inside the function remains the same and is equal to "Andrey", but not "Rud Sergey".

Passing arguments by reference

Third way is the transmission of the address ( links) variable, not its value. References in PHP are not very successful, unlike other programming languages. However, I will tell you the only correct way to pass 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 below, as a result, the PHP developers themselves decided to abandon them, so we will not talk about them.

So, the RIGHT way to pass an argument by reference in PHP 5.3 and above is as follows:

Function sayHi(& $name)(

We added an ampersand (&) icon in the function description itself - this icon means that we do not accept the value of a variable, but a reference (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 of them change, since they refer to the same value in memory.

And as a result we have:

//we accept not a value, but a reference to a value echo "Hi, ".$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 is what we are trying to do:

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


Result:

Variable $c does not remember its value, it is created anew each time. We need to make sure that our local variable $c remembered its value after the function was executed, for this they use the keyword static:

// counter, made static echo "Hi, ".$name."!
"; $c++; // increment the counter by 1 echo "Total 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 the function, instead of displaying something on the screen, puts everything in a variable and gives this variable to us. And we are already deciding what to do with it. For example, take this function, it squares a number:

Result:

Let's make it so that instead of displaying it on the screen, it returns the result of execution. The return keyword is used for this:

Result:

Now we can use this in various ways:

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

Result:

I draw your attention to the fact that the key word return does not just return a value, but completely interrupts the function, that is, all code that is below the keyword return never be fulfilled. In other words, return for functions also works like break for cycles:

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

Result:

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

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 the use of recursion is the most obvious and simple option. Example:

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

Result:

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

Strong typing in PHP (type qualification)

PHP has taken small steps towards strong typing so that we can pre-specify 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 pass a number to it. Unfortunately, for the time being, we can only specify the type for (array), and since PHP 5.4, such an option has been added as callable:

callable checks if the passed value can be called as a function. Callable can be either a function name given by a string variable, or an object and the name of a method to be called. But we will talk about objects and methods later (this is the section of object-oriented programming), and 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 the situation, we pass arguments to the 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 either. But this does not mean that they are gone - they are still passed to 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 the 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 safely use the functions for your needs.

If someone has a desire to get hands on, but no ideas 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 soon! If something is not clear, feel free to ask your questions in the comments!

Last update: 1.11.2015

When using variables and functions, consider the scope of variables. The scope defines the scope of the accessibility of this variable.

Local variables

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

In this case, the local variable $result is defined in the get() function. And from the general context, we cannot refer to it, that is, write $a = $result; you can't, 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 ends, their value is saved. With each new call, the function uses the previously stored value. For example:

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

If the $counter variable were a normal non-static variable, then the getCounter() function would output 1 each time it was called.

As a rule, 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. The global keyword is used to define global variables:1

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

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

AT JavaScript global variables are of great importance, and they are constantly used when writing scripts. PHP global variables- a rarely noticed phenomenon, especially if you use OOP however, it is worth knowing about them. If you don't know about global variables in PHP then this article will fill that knowledge gap.

Exists global and local variables. Global, as their name implies, are available throughout the entire script, including inside functions. Local variables are declared within functions and are only accessible within them.

Let's look at this example php code:

$x = 5; // Create a variable (of course, it's global)
function myFunc1() (
$x = 7; // Local variable, only available inside the function
}
function myFunc2() (
global $x; // Indicate that $x is a global variable
$x = 7; // Change the global variable $x
}
myFunc1();
echo $x; // Output 5
echo "
";
myFunc2();
echo $x; // Outputs 7
print_r($GLOBALS); // Displays all global variables
?>

When withdrawing $x the first time we got 5 , because inside the function myFunc1() we have created a local variable $x, which has nothing to do with a global variable $x does not have. Thus, by changing the value of a local variable, we did not change it in any way in the global one.

In 2nd functions we before use $x indicated that inside this function $x must be global, that is, we got access to a global variable inside the function. As a result, we changed its value, which we echo and reported.

And at the end of the script, I output an associative array $GLOBALS, which contains all global variables in the script. Of course, there are not only $x, but also a lot of service variables. Both inside the function and outside the function, you can always access any element in this array and change it.

Now you already know exactly what is global variables in PHP and can work with them if needed.

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 include and required files. For example:

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

Here the $a variable will be available inside the included script b.inc . However, the definition (body) of a user-defined function defines 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 */

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

test();
?>

This script will not generate any output because the echo statement points to the local version of $a , and it has not been assigned a value within that scope. You may have noticed that this is slightly different from the C language 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 because people can inadvertently change a global variable. In PHP, if a global variable is to be used inside a function, it must be declared global inside the function definition.

Keyword global

First use case 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 . After defining $a and $b as global within the 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 can be processed by a function.

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

$GLOBALS is an associative array whose key is the name and whose value is the content of the global variable. Note that $GLOBALS exists in any scope, this is because $GLOBALS is a superglobal. The following 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 scope
// 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 of a 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 function's local scope, but does not lose its value when program execution exits that scope. Consider the following example:

Beispiel #4 Demonstrating the need for static variables

functiontest()
{
$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 variable $a disappears when the function exits. To write a useful counter function that will not lose the current value of the counter, the $a variable is declared static:

Beispiel #5 Static variables example

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

Now $a will only be initialized the first time the function is called, and each function call test() will output the value of $a and increment it.

Static variables also make it possible to work with recursive functions. A recursive function is a function that calls itself. When writing a recursive function, you need to be careful, because it is possible to make the recursion infinite. You must ensure that there is an adequate way to end the recursion. The following simple function counts up to 10 recursively, using the $count static variable 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

functionfoo()(
static $int = 0 ; // right
static $int = 1 + 2 ; // invalid (because it's an expression)
static $int = sqrt(121); // invalid (because it's also an expression)

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

Comment:

Static declarations are evaluated at script compilation time.

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

The Zend Engine 1 at the heart of 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, actually 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 object to 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 assigning a reference to a static variable, it does not remembered when you call the function &get_instance_ref() a second time.

This lesson focuses on the scope of PHP variables. Explains the difference between local and global scope, shows how to access global variables inside 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 little confusing. Fortunately PHP's rules in this regard are very easy to understand (compared to other programming languages).

What is scope?

Variable scope is the context within which a 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 within the function in which they were defined

Variable scope, and especially local scope, 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 name. By limiting the scope to the local context, you define the boundaries of the code that can access the variable, which makes the code more robust, modular, and easier to debug.

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

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

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

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

In this script, we have created two variables:

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

After the variable and function are created, the script calls sayHello() , which prints "Hi 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 of the function, it is available anywhere in the script, so "Zoya" is displayed.
  • $localName will only be available inside the sayHello() function. Because the echo expression is outside the function, PHP does not allow access to the local variable. Instead, PHP assumes that the code will create a new variable named $localName , which will default to an 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 outside the function just write her name. 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; // Accessing the global variable $globalVariable )

If you don't, then 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 as global. She can then access the variable and output its value ("Zoya").

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 the 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 with a GET request
  • $_POST - contains a list of all form fields submitted by the browser using a POST request
  • $_COOKIE - contains a list of all cookies sent by the browser
  • $_REQUEST - contains all key/value combinations contained in $_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 the variables contained in the script's request URL string, and display them on the page:

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

Hey Fred!

A warning! In a real script, this data transfer should never be used due to weak security. You should always check or filter the data.

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

"; ) sayHello(); // Displays "Hello Zoya!" ?>

Static variables: they are somewhere around

When you create a local variable within a function, it only exists while the function is running. When the function terminates, 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-sufficient and always work the same way 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; )

Consider a situation where it is convenient to use a static variable. Let's say you create a function that, when called, creates a widget and prints out 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 get the following result:

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

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

"; 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... 1 we have already created. 2 we have already created. 3 we have already created.

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

That's all! Refer often to the PHP documentation.