Home >Backend Development >PHP Problem >How to use global in php

How to use global in php

(*-*)浩
(*-*)浩Original
2019-09-09 10:30:2319134browse

Global variables and "global" keyword

How to use global in php

PHP defines some "Superglobals" variables by default. These Variables are automatically globalized and can be called anywhere in the program, such as $_GET and $_REQUEST, etc. They usually come from data or other external data, and using these variables usually does not cause problems because they are basically not writable.

But you can use your own global variables.

Using the keyword "global" you can import global data into the local scope of a function. If you don't understand "variable usage range", please refer to the relevant instructions in the PHP manual.

The following is a demonstration example using the "global" keyword:

<?php教程
$my_var = &#39;Hello World&#39;;
test_global();
function test_global() {
    // Now in local scope
     // the $my_var variable doesn&#39;t exist
     // Produces error: "Undefined variable: my_var"
    echo $my_var;
    // Now let&#39;s important the variable
    global $my_var;
    // Works:
    echo $my_var;
}
?>

As you can see in the above example, the "global" keyword is used to import global variables . It looks like it works very well and is very simple, so why do we have to worry about using the "global" keyword to define global data?

Let me explain the use of the global variable global to those who are new to the industry. "Global variable", the two words "global" in this noun already tell us that this variable can be used everywhere. Let's look at an example first:

<?php
$a = 1;
$b = 2;
function Sum()
{
    global $a, $b; //在里面声明为全局变量
    $b = $a + $b;
}
Sum();
echo $b;
?>

Result: 3

If there is no global variable global cannot obtain the values ​​​​of $a and $b in the method, so if you want to use external variables in the method, you need to declare the variable as a global variable first, so that it can be used, which is very convenient.

The above is the detailed content of How to use global in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn