搬砖笔记:浅谈PHP Static静态变量

static用法

  1. static 放在函数内部修饰变量

  2. static放在类里修饰属性,或方法

  3. static放在类的方法里修饰变量

  4. static修饰在全局作用域的变量

所表示的不同含义如下:

1、在函数执行完后,变量值仍然保存

<?php
function testStatic() {
    static $val = 1;
    echo $val;
    $val++;
}
testStatic();   //output 1
testStatic();   //output 2
testStatic();   //output 3
?>

2、修饰类的属性或方法,可以通过类名访问,如果是修饰的是类的属性,保留值

<?php
class Person {
    static $id = 0;
 
    function __construct() {
        self::$id++;
    }
 
    static function getId() {
        return self::$id;
    }
}
echo Person::$id;   //output 0
echo "<br/>";
 
$p1=new Person();
$p2=new Person();
$p3=new Person();
 
echo Person::$id;   //output 3
?>

3、修饰类的方法里面的变量,不论是静态方法还是对象方法

<?php
class Person {
    static function tellAge() {
        static $age = 0;
        $age++;
        echo "The age is: $age";
    }
}
echo Person::tellAge(); //output 'The age is: 1'
echo Person::tellAge(); //output 'The age is: 2'
echo Person::tellAge(); //output 'The age is: 3'
echo Person::tellAge(); //output 'The age is: 4'

4、修饰全局作用域的变量,没有实际意义

<?php
static $name = 1;
$name++;
echo $name;
?>

另外:考虑到PHP变量作用域;如下代码,这3个变量是不相互影响的

<?php
include 'ChromePhp.php';
 
$age=0;
$age++;
 
function test1() {
    static $age = 100;
    $age++;
    ChromePhp::log($age);  //output 101
}
 
function test2() {
    static $age = 1000;
    $age++;
    ChromePhp::log($age); //output 1001
}
 
test1();
test2();
ChromePhp::log($age); //outpuut 1
?>

6、PHP里面只有全局作用域和函数作用域,没有块作用域

<?php
include 'ChromePhp.php';
 
$age = 0;
$age++;
 
for ($i=0; $i<10; $i++) {
    $age++;
}
ChromePhp::log($i);   //output 10;
ChromePhp::log($age); //output 11;
?>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值