PHP中abstract类中有abstract方法是否最先执行abstract方法,然后才执行其他方法?
rt
<br />abstract class Node {<br /> private $debugMessages;<br /> <br /> public function __construct() {<br /> $this->debugMessages = array();<br /> $this->debug(__CLASS__.' constructor called.');<br /> }<br /> <br /> public function __destruct() {<br /> $this->debug(__CLASS__.' destructor called.');<br /> $this->dumpDebug();<br /> }<br /> <br /> protected function debug($msg) {<br /> $this->debugMessages[] = $msg;<br /> }<br /> <br /> private function dumpDebug() {<br /> echo implode('<br />', $this->debugMessages);<br /> }<br /> <br /> public abstract function getView();<br /> }<br /> <br /> <br /> class ForumTopic extends Node {<br /> private $debugMessages;<br /> <br /> public function __construct() {<br /> parent::__construct();<br /> $this->debug(__CLASS__.' constructor called.');<br /> }<br /> <br /> public function __destruct() {<br /> $this->debug(__CLASS__.' destructor called.<b>%本文@来源gao@!dai!ma.com搞$$代^@码!网</b><strong>搞代gaodaima码</strong>');<br /> parent::__destruct();<br /> }<br /> <br /> public function getView() {<br /> return 'This is a view into '.__CLASS__.'<br />';<br /> }<br /> }<br /> <br /> $forum = new ForumTopic();<br /> echo $forum->getView();<br />
执行结果:
This is a view into ForumTopic
Node constructor called.
ForumTopic constructor called.
ForumTopic destructor called.
Node destructor called.
但没有new ForumTopic()怎么能够调用执行getView()?
——解决方案——————–
执行顺序:
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;
}
你就可以看到真正的执行顺序
——解决方案——————–
一个是函数,一个是变量。get_class()需要对象参数。
你写的例子是重载了。
“但没有new ForumTopic()怎么能够调用执行getView()? ”你这句话没弄懂,怎么跟你的例子有点矛盾