对象接口
2016-03-24 10:25
316 查看
使用接口(interface),可以指定某个类必须实现哪些方法,但不需要定义这些方法的具体内容。
接口是通过 interface 关键字来定义的,就像定义一个标准的类一样,但其中定义所有的方法都是空的。
接口中定义的所有方法都必须是公有,这是接口的特性。
要实现一个接口,使用 implements 操作符。类中必须实现接口中定义的所有方法,否则会报一个致命错误。类可以实现多个接口,用逗号来分隔多个接口的名称。
Note:
实现多个接口时,接口中的方法不能有重名。
Note:
接口也可以继承,通过使用 extends 操作符。
Note:
类要实现接口,必须使用和接口中所定义的方法完全一致的方式。否则会导致致命错误。
接口中也可以定义常量。接口常量和类常量的使用完全相同,但是不能被子类或子接口所覆盖。
Example #1 接口示例
Example #2 使用接口常量
接口是通过 interface 关键字来定义的,就像定义一个标准的类一样,但其中定义所有的方法都是空的。
接口中定义的所有方法都必须是公有,这是接口的特性。
实现(implements)
要实现一个接口,使用 implements 操作符。类中必须实现接口中定义的所有方法,否则会报一个致命错误。类可以实现多个接口,用逗号来分隔多个接口的名称。Note:
实现多个接口时,接口中的方法不能有重名。
Note:
接口也可以继承,通过使用 extends 操作符。
Note:
类要实现接口,必须使用和接口中所定义的方法完全一致的方式。否则会导致致命错误。
常量
接口中也可以定义常量。接口常量和类常量的使用完全相同,但是不能被子类或子接口所覆盖。
范例
Example #1 接口示例<?php // 声明一个'iTemplate'接口 interface iTemplate { public function setVariable($name, $var); public function getHtml($template); } // 实现接口 // 下面的写法是正确的 class Template implements iTemplate { private $vars = array(); public function setVariable($name, $var) { $this->vars[$name] = $var; } public function getHtml($template) { foreach($this->vars as $name => $value) { $template = str_replace('{' . $name . '}', $value, $template); } return $template; } } // 下面的写法是错误的,会报错,因为没有实现 getHtml(): // Fatal error: Class BadTemplate contains 1 abstract methods // and must therefore be declared abstract (iTemplate::getHtml) class BadTemplate implements iTemplate { private $vars = array(); public function setVariable($name, $var) { $this->vars[$name] = $var; } } ?>
Example #2 使用接口常量
<?php interface a { const b = 'Interface constant'; } // 输出接口常量 echo a::b; // 错误写法,因为常量不能被覆盖。接口常量的概念和类常量是一样的。 class b implements a { const b = 'Class constant'; } ?>
相关文章推荐
- 拉链法(链地址法)
- .dll动态文件
- 格式布局(课堂代码)
- Leetcode 125. Valid Palindrome
- 计算矩阵行列式时奇排列与偶排列的判定
- JavaScript 笔记 - <script>标签 defer属性 (延迟脚本)
- ScrollView嵌套ListView
- 数据库:自己理解的“数据库事务隔离级别”
- seconds_behind_master监控复制推延的不足及pt-heartbeat改进方法
- javaScript基础
- iOS9 HTTP 不能正常使用的解决办法
- C++第二次试验——标准体重
- 订单数字提醒的实现
- 地址重定向
- JQuery常用函数及功能小结--转载
- (笔记)AT91SAM9260的启动过程详细解说
- 浅谈midi与cocos的交互
- Interview Vocabulary
- Toast显示和关闭自个控制的方法
- c++实验2-分段函数求值