先看一段代码:
1
<?php
2
class User
3
{
4
static private $counter = 1;
5
6
public function __construct()
7
{
8
self::$counter++;
9
}
10
11
static public function getCount()
12
{
13
return self::$counter;
14
}
15
16
public function __destruct()
17
{
18
self::$counter--;
19
}
20
}
21
22
echo 'run static getCount:'.User::getCount().'<br>';
23
24
$user1 = new User();
25
$user2 = new User();
26
echo 'run user1 getCount:'.$user1->getCount().'<br>';
27
unset($user1);
28
echo 'run user2 getCount:'.$user2->getCount();
29
30
?>
31
32
运行结果:
33
34
run static getCount:1
35
run user1 getCount:3
36
run user2 getCount:2

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

通过如上代码可以得到相关结论:
1、静态变量和静态方法,不需要new一个对象就可以直接使用;
2、当对象被unset后,仍然能够继续使用。
由此可知,静态变量和静态方法,在进程创建的时候就被创建了,而不是在对象创建的时候才被创建,并且其生命周期同该进程的生命周期一样长,其占用的系统资源是初始化进程申请资源的一部分。
至于apache是如何给进程分配内存的,请看下一篇 简单介绍apahce内存管理机制 。
注:每刷新一下页面,就会使服务器端产生一个进程(或线程)处理该请求。