• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

PHP中abstract种中有abstract方法是否最先执行abstract方法,然后才执行其他方法

php 搞代码 3年前 (2022-01-24) 21次浏览 已收录 0个评论

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()?

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;
}
你就可以看到真正的执行顺序

——解决方案——————–

引用:

还有请问__CLASS__与get_class()有什么本质的区别?好像其中一个总是指向一个类,而另一个则根据类的域不同而指向不同的类,具体我记不清楚了

一个是函数,一个是变量。get_class()需要对象参数。

你写的例子是重载了。

“但没有new ForumTopic()怎么能够调用执行getView()? ”你这句话没弄懂,怎么跟你的例子有点矛盾


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:PHP中abstract种中有abstract方法是否最先执行abstract方法,然后才执行其他方法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址