變數和變數作用域 | PHP 基礎知識

WBOY
發布: 2024-07-19 02:18:10
原創
399 人瀏覽過

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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!