在看別人項(xiàng)目過程中噪珊,看到函數(shù)里面很多static修飾的變量晌缘,關(guān)于static修飾的變量齐莲,作用域,用法越看越困惑磷箕,所以查了下資料选酗。
static用法如下:
1.static 放在函數(shù)內(nèi)部修飾變量
2.static放在類里修飾屬性,或方法
3.static放在類的方法里修飾變量
4.static修飾在全局作用域的變量
所表示的不同含義如下:
1.在函數(shù)執(zhí)行完后岳枷,變量值仍然保存
如下所示:
functiontestStatic() {
static$val= 1;
echo$val;
$val++;
}
testStatic();//output 1
testStatic();//output 2
testStatic();//output 3
?>
2.修飾屬性或方法芒填,可以通過類名訪問,如果是修飾的是類的屬性空繁,保留值
如下所示:
classPerson {
static$id= 0;
function__construct() {
self::$id++;
}
staticfunctiongetId() {
returnself::$id;
}
}
echoPerson::$id;//output 0
echo"
";
$p1=newPerson();
$p2=newPerson();
$p3=newPerson();
echoPerson::$id;//output 3
?>
3.修飾類的方法里面的變量
如下所示:
classPerson {
staticfunctiontellAge() {
static$age= 0;
$age++;
echo"The age is:$age
";
}
}
echoPerson::tellAge();//output 'The age is: 1'
echoPerson::tellAge();//output 'The age is: 2'
echoPerson::tellAge();//output 'The age is: 3'
echoPerson::tellAge();//output 'The age is: 4'
?>
4.修飾全局作用域的變量氢烘,沒有實(shí)際意義(存在著作用域的問題,詳情查看)
如下所示:
static$name= 1;
$name++;
echo$name;
?>
另外:考慮到PHP變量作用域
include'ChromePhp.php';
$age=0;
$age++;
functiontest1() {
static$age= 100;
$age++;
ChromePhp::log($age);//output 101
}
functiontest2() {
static$age= 1000;
$age++;
ChromePhp::log($age);//output 1001
}
test1();
test2();
ChromePhp::log($age);//outpuut 1
?>
可以看出:這3個變量是不相互影響的家厌,另外,PHP里面只有全局作用域和函數(shù)作用域椎工,沒有塊作用域
如下所示:
include'ChromePhp.php';
$age= 0;
$age++;
for($i=0;$i<10;$i++) {
$age++;
}
ChromePhp::log($i);//output 10;
ChromePhp::log($age);//output 11;
?>