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

The four major scopes of PHP variables

藏色散人
Release: 2023-04-08 08:22:02
forward
3928 people have browsed it

PHP variable scope

● local

● global

● static

● parameter

Local scope, global scope

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

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
Copy after login

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;
Copy after login

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();
Copy after login

Parameter scope (formal parameter)

Parameter declaration as part of the function declaration.

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

Small addition:

Print array method:

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

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!

Related labels:
php
source:learnku.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template