Fenying

Angus’ Home.


27 Sep 2014

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

该文章迁移自作者的旧博客站点。
源地址:http://fenying.blog.163.com/blog/static/102055993201482711112446/

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

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

<?php
$a = new A;
$b = new B;

##############################


# order should be: 

A::__construct();
B::__construct();
B::__destruct();
A::__destruct();

但是下面的代码却未必:

<?php
class A {
	protected static $_inst;
	protected function __construct() {
		echo __METHOD__.'<br>';;
	}

	public static function getInst() {
		if (!self::$_inst)
			self::$_inst = new self;
		return self::$_inst;
	}

	public function __destruct() {
		echo __METHOD__.'<br>';;
	}
}

class B {
	protected static $_inst;
	protected function __construct() {
		echo __METHOD__.'<br>';;
	}
	public function __destruct() {
		echo __METHOD__.'<br>';;
	}

	public static function getInst() {
		if (!self::$_inst)
			self::$_inst = new self;
		return self::$_inst;
	}
}

class C {
	public function __construct() {
		echo __METHOD__.'<br>';;
	}

	public function __destruct() {
		echo __METHOD__.'<br>';;
	}
}

class D {
	public function __construct() {
		echo __METHOD__.'<br>';;
	}

	public function __destruct() {
		echo __METHOD__.'<br>';;
	}
}

A::getInst();
B::getInst();
$a = new C;
$b = new D;

结果是

<?php
A::__construct();
B::__construct();
C::__construct();
D::__construct(); # Construction order is OK
D::__destruct();
C::__destruct();
A::__destruct(); # !!! what, A prior to B?????
B::__destruct(); # !!!

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

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

comments powered by Disqus