PHP 类静态成员的奇怪析构现象

该文章根据 CC-BY-4.0 协议发表,转载请遵循该协议。
本文地址:https://fenying.net/post/2014/09/27/destruct-order-of-class-static-properties-in-php/

本文介绍 PHP 中静态成员属性的析构顺序问题。

我们知道PHP的对象是先构造的后析构,比如

 1<?php
 2$a = new A;
 3$b = new B;
 4
 5##############################
 6
 7
 8# order should be: 
 9
10A::__construct();
11B::__construct();
12B::__destruct();
13A::__destruct();

但是下面的代码却未必:

 1<?php
 2class A {
 3	protected static $_inst;
 4	protected function __construct() {
 5		echo __METHOD__.'<br>';;
 6	}
 7
 8	public static function getInst() {
 9		if (!self::$_inst)
10			self::$_inst = new self;
11		return self::$_inst;
12	}
13
14	public function __destruct() {
15		echo __METHOD__.'<br>';;
16	}
17}
18
19class B {
20	protected static $_inst;
21	protected function __construct() {
22		echo __METHOD__.'<br>';;
23	}
24	public function __destruct() {
25		echo __METHOD__.'<br>';;
26	}
27
28	public static function getInst() {
29		if (!self::$_inst)
30			self::$_inst = new self;
31		return self::$_inst;
32	}
33}
34
35class C {
36	public function __construct() {
37		echo __METHOD__.'<br>';;
38	}
39
40	public function __destruct() {
41		echo __METHOD__.'<br>';;
42	}
43}
44
45class D {
46	public function __construct() {
47		echo __METHOD__.'<br>';;
48	}
49
50	public function __destruct() {
51		echo __METHOD__.'<br>';;
52	}
53}
54
55A::getInst();
56B::getInst();
57$a = new C;
58$b = new D;

结果是

1<?php
2A::__construct();
3B::__construct();
4C::__construct();
5D::__construct(); # Construction order is OK
6D::__destruct();
7C::__destruct();
8A::__destruct(); # !!! what, A prior to B?????
9B::__destruct(); # !!!

即是说,类静态成员的析构顺序,依照类的定义顺序。

comments powered by Disqus