Home  >  Article  >  Backend Development  >  The four major scopes of PHP variables

The four major scopes of PHP variables

藏色散人
藏色散人forward
2020-01-15 11:46:593879browse

PHP variable scope

● local

● global

● static

● parameter

Local scope, global scope

<?php
$x = 50; // 全局变量
function myTest()
{
    $y = 100; // 局部变量
}

PHP global keyword

The global keyword is used to access global variables within a function.

To call global variables defined outside the function within a function, you can add the global keyword before the variables in the function.

<?php
$x = 50;
$y = 100;
function myTest()
{
    global $x, $y;
    $y = $x + $y;
}
myTest();
echo $y;  // 输出 150

PHP stores all global variables in an array called $GLOBALS.

So the above code can be written in another way:

<?php
$x = 50;
$y = 100;
function myTest()
{
    $GLOBALS[&#39;y&#39;] = $GLOBALS[&#39;x&#39;] + $GLOBALS[&#39;y&#39;];
} 
myTest();
echo $y;

PHP Static scope

PHP When a function completes, all its variables are usually will be deleted. In order to prevent some local variables from being deleted, you can use the static keyword when declaring the variable for the first time.

<?php
function myTest()
{
    static $x = 0;
    echo $x;
    $x++;
    echo PHP_EOL;
}
myTest();
myTest();
myTest();

Parameter scope (formal parameter)

Parameter declaration as part of the function declaration.

<?php
function myTest($x)
{
    echo $x;
}
myTest(&#39;Galois&#39;);
myTest(8888);

Small addition:

Print array method:

echo &#39;<pre class="brush:php;toolbar:false">&#39;;
print_r($arr);

Related recommendations:php tutorial

The above is the detailed content of The four major scopes of PHP variables. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete