PHP中abstract类中有abstract方法是否最先执行abstract方法,然后才执行其他方法?
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()?
php
destructor
constructor
function
class
------解决方案--------------------执行顺序:
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()? ”你这句话没弄懂,怎么跟你的例子有点矛盾