1. 程式人生 > 程式設計 >PHP變數的作用範圍例項講解

PHP變數的作用範圍例項講解

區域性變數

  • 在函式內部定義的變數
  • 變數的作用範圍就是這個函式。

案例

<?php

function test(){
	$a=10;
	echo $a;
}
test();
echo "<hr />";
echo $a;
?>

案例結果

在這裡插入圖片描述

全域性變數

  • 在php 指令碼中,函式外部定義的變數
  • 變數的作用域為整個PHP 指令碼。

案例

<?php
$a=10;
function test(){
	echo $a;
}
test();
echo "<hr />";
echo $a;
?>

案例結果

在這裡插入圖片描述

在函式中使用函式全域性變數?

  • 1. 傳參
  • 2. 宣告方式 global
  • 3. 常量的作用域,是超全域性

案例:宣告方式 global

<?php
$a = 10;
function test(){
	global $a;
	echo $a;
}
test();
?>

案例結果

在這裡插入圖片描述

案例:常量

<?php
define("NAME","WCP");
function test(){
	echo NAME;
}
test();
?>

案例結果

在這裡插入圖片描述

靜態變數

  • 在函式內部定義
  • 用static 修飾符修飾
  • 僅在函式初次執行時被初始化。

案例

<?php
function test(){
	static $a = 0;
	echo ++$a."|";
}
test();
test();
test();
?>

案例結果

PHP變數的作用範圍例項講解PHP變數的作用範圍例項講解

到此這篇關於PHP變數的作用範圍的文章就介紹到這了,更多相關PHP變數的作用範圍內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!