PHP variable scope, global, static and other keywords

不言
Release: 2023-04-02 16:14:02
Original
1897 people have browsed it

This article mainly introduces the scope, global, static and other keywords of PHP variables. It has certain reference value. Now I share it with you. Friends in need can refer to it

  1. Local and global scope

Variables defined in the function body in php are local variables, and variables defined outside the function are called global variables

 <?php
$x=5; // 全局变量function myTest()
{
    $y=10; // 局部变量
    echo "<p>测试函数内变量:<p>";
    echo "变量 x 为: $x";
    echo "<br>";
    echo "变量 y 为: $y";
} 

myTest();

echo "<p>测试函数外变量:<p>";
echo "变量 x 为: $x";
echo "<br>";
echo "变量 y 为: $y";?>
Copy after login

2 . global keyword

Global variables cannot be used in the function body in php. If you want to use them, you need to use the global keyword to declare them before use

<?php
$x=5;
$y=10;
 
function myTest()
{    global $x,$y;
    $y=$x+$y;
}
 
myTest();
echo $y; // 输出 15?>
Copy after login

3.static scope

When the function finishes running, the variables within the function will be eliminated. If you still need to use them and do not want them to be deleted, use the static keyword. Only used when declaring a variable for the first time.

<?php
function myTest()
{    static $x=0;
    echo $x;
    $x++;
}
 
myTest();
myTest();
myTest();?>
Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

Commonly used array functions in PHP

Introduction to static variables in PHP

The above is the detailed content of PHP variable scope, global, static and other keywords. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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