rt
abstract class Node {
private $debugMessages;
public function __construct() {
$this->debugMessages = array();
$this->debug(__CLASS__.' constructor called.');
}
public function __destruct() {
$this->debug(__CLASS__.' destructor called.');
$this->dumpDebug();
}
protected function debug($msg) {
$this->debugMessages[] = $msg;
}
private function dumpDebug() {
echo implode('<br />', $this->debugMessages);
}
public abstract function getView();
}
class ForumTopic extends Node {
private $debugMessages;
public function __construct() {
parent::__construct();
$this->debug(__CLASS__.' constructor called.');
}
public function __destruct() {
$this->debug(__CLASS__.' destructor called.');
parent::__destruct();
}
public function getView() {
return 'This is a view into '.__CLASS__.'<br />';
}
}
$forum = new ForumTopic();
echo $forum->getView();
执行结果:
This is a view into ForumTopic
Node constructor called.
ForumTopic constructor called.
ForumTopic destructor called.
Node destructor called.但没有new ForumTopic()怎么能够调用执行getView()?phpdestructorconstructorfunctionclass
abstract class Node {
private $debugMessages;
public function __construct() {
$this->debugMessages = array();
$this->debug(__CLASS__.' constructor called.');
}
public function __destruct() {
$this->debug(__CLASS__.' destructor called.');
$this->dumpDebug();
}
protected function debug($msg) {
$this->debugMessages[] = $msg;
}
private function dumpDebug() {
echo implode('<br />', $this->debugMessages);
}
public abstract function getView();
}
class ForumTopic extends Node {
private $debugMessages;
public function __construct() {
parent::__construct();
$this->debug(__CLASS__.' constructor called.');
}
public function __destruct() {
$this->debug(__CLASS__.' destructor called.');
parent::__destruct();
}
public function getView() {
return 'This is a view into '.__CLASS__.'<br />';
}
}
$forum = new ForumTopic();
echo $forum->getView();
执行结果:
This is a view into ForumTopic
Node constructor called.
ForumTopic constructor called.
ForumTopic destructor called.
Node destructor called.但没有new ForumTopic()怎么能够调用执行getView()?phpdestructorconstructorfunctionclass
ForumTopic::__construct()
Node::__construct()
Node::debug()
ForumTopic::debug()
ForumTopic::getView()
ForumTopic::__destruct()
ForumTopic::debug()
Node::__destruct()
Node::debug()
Node::dumpDebug()
你是先执行echo $forum->getView();所以先输出:This is a view into ForumTopic
在对象的销毁的时候,父类析构函数把$debugMessages中的所有数据打印出来了。就下面那样:
Node constructor called.
ForumTopic constructor called.
ForumTopic destructor called.
Node destructor called.
__CLASS__指是的当前类get_class($obj)指的是实例$obj的类
protected function debug($msg) {
$this->debugMessages[] = $msg;
}
改成
protected function debug($msg) {
echo $msg;
}
你就可以看到真正的执行顺序
LZ的意思是不是不要创建实例,直接调用getView方法。如果是就用类名::方法名。
ForumTopic::getView()