- 静态属性有两种,局部静态跟全局静态,局部静态是只在函数作用域内有用,外部引用时会报错,全局静态则在函数内外部都可以引用且改变值。静态属性只会初始化一次,然后就会存在一块固定的内存块里。
function test(){
static $var = 5;
$var++;
echo $var . ' ';
}
test();
test();
test();
echo $var;
function static_global(){
global $glo;
$glo++;
echo $glo.'<br>';
}
static_global();
static_global();
static_global();
echo $glo . '<br>';
- 关于静态方法与非静态方法之间调用的注意事项,下面举例说明:
class Banji{
public static $nums = 0;
public $name = '';
public function __construct($name){
$this->name = $name;
self::$nums++;
}
public function nums(){
echo self::$nums;
echo '<br>';
echo $this->name;
echo '<br>';
}
public static function test(){
echo self::$nums;
echo '<br>';
}
public static function test1(){
echo self::$nums;
echo '<br>';
echo $this->name;
echo '<br>';
}
public static function test2(){
self::nums();
}
public static function test3(){
$this->nums();
}
public function test4(){
self::test();
}
}
$student = new Banji('Susunma');
$student->nums();
$student = new Banji('Susunma1');
$student->nums();
$student = new Banji('Susunma2');
$student->nums();
$student->test();
$student->test1();
Banji::test();
Banji::test1();
$student->test2();
$student->test3();
$student->test4();