首页  >  文章  >  后端开发  >  变量和变量作用域 | PHP 基础知识

变量和变量作用域 | PHP 基础知识

WBOY
WBOY原创
2024-07-19 02:18:10542浏览

Variable & Variable Scope | PHP Fundamentals

Create Variable in PHP

The rules when you create variables in PHP:

  1. Variable declaration with dollar ($) followed by variable name
  2. Variable name must start with a letter or underscore (_)
  3. Variable name is case-sensitive

Valid variables:

$name = "Gunawan"; //valid
$Name = "Gunawan"; //valid
$_name = "Gunawan; //valid

Not valid variables:

$4name = "Gunawan"; //not valid
$user-name = "Gunawan"; //not valid
$this = "Gunawan"; //not valid

Variable Scope

PHP has 3 variable scopes:

  1. Global
  2. Local
  3. Static

Global scope

$name = "Gunawan";

function get_name() {
echo $name; // not valid
}

get_name();

To access a global variable within a function you must declare a global variable with the keyword 'global' within a function.

$name = "Gunawan";

function get_name() {
global $name;
echo $name; // valid
}

get_name();

Use Array GLOBALS to Access Global Variable

The second way to access global variables is to use a global array.

$name = "Gunawan";

function get_name() {
echo $GLOBALS['name']; // valid
}

get_name();

Static Variable

function test() {
static $number = 0;
echo $number;
$number++;
}

Variable Super Global in PHP:

  1. $GLOBALS
  2. $_SERVER
  3. $_GET
  4. $_POST
  5. $_FILES
  6. $_COOKIE
  7. $_SESSION
  8. $_REQUEST
  9. $_ENV

Download my repository php fundamental from my github.

以上是变量和变量作用域 | PHP 基础知识的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn