关于static
2018-01-11 本文已影响19人
geeooooz
<?php
//static用法
// 1.static 放在函数内部修饰变量
//在函数执行完后,变量值仍然保存
function testStatic(){
static $val= 1;
echo $val;
$val++;
}
testStatic();//output 1
testStatic();//output 2
testStatic();//output 3
// 2.static放在类里修饰属性,或方法
// 修饰属性或方法,可以通过类名访问,如果是修饰的是类的属性,保留值
class Person {
static $id= 0;
function __construct() {
self::$id++;
}
static function getId() {
echo self::$id;
}
}
echo Person::$id;//output 0
echo"";
$p1=new Person();//每次实例化类都会+1
$p2=new Person();
$p3=new Person();
echo Person::$id;//output 3
// 3.static放在类的方法里修饰变量
// 修饰类的方法里面的变量
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.static修饰在全局作用域的变量
//修饰全局作用域的变量,没有实际意义(存在着作用域的问题,详情查看)
static $name= 1;
$name++;
echo $name;