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

php中的接口interface

php 搞代码 4年前 (2022-01-22) 15次浏览 已收录 0个评论

* 接口

* 1.使用关键字:interface

* 2.类是对象的模板,接口是类的模板

* 3.接口看作是一个特殊的类

* 4.接口中的方法,只声明不实现,与抽象类一样

* 5.接口中的方法必须是public,支持static

* 6.接口中可以声明类常量const,但不允许被类或子接口覆盖

* 7.用类实现一个接口使用implements 关键字

* 8.一个类可以实现多个接口,多个接口之间用逗号分开

* 9.接口之间也可以使用关键字extends继承

* 10.一个类实多个接口时,方法不可以重名

//声明接口:动物

if (!interface_exists('Animal')) {    interface Animal    {        //接口常量        const status = 'viable'; //能存活的                //接口方法:饲养时吃什么        public function feeding($foods);    }}//声明类Cat,并实现接口Animalif (interface_exists('Animal')) {    class Cat implements Animal    {        private $name = '猫';                //在类中必须实现接口中的方法feeding()        public function feeding($foods)        {            return $this->name.'吃'.$foods;        }    }<strong style="color:transparent">本文来源gao@daima#com搞(%代@#码@网&</strong><strong>搞gaodaima代码</strong>}//实例化Dog类,echo (new Cat())->feeding('老鼠');echo '<hr>';//再定义一个接口:动物的特性if (!interface_exists('Feature')) {    interface Feature    {                //接口方法        public function hobby($hobby);    }}//声明一个类Dog,实现了二个接口: Animal,Featureif (interface_exists('Animal') && interface_exists('Feature')) {    class Dog implements Animal, Feature    {        private $name = '狗';                //必须实现接口Animal中的feeding()方法        public function feeding($foods)        {//            return $this->name.'吃'.$foods;            //改成链式            echo  $this->name.'吃'.$foods;            return $this;        }                //必须实现接口Feature中的hobby()方法        public function hobby($hobby)        {//            return $hobby;                        //改成链式            echo $hobby;            return $this;        }    }}

//实例化Dog类

echo (new Dog())->feeding('肉');echo (new Dog())->hobby('忠诚,勇敢,不离不弃~~');

//大家想想如何将上面的二个方法调用改成链式?

//注意:先把上面的实例化调用语句注释掉,否则下面的链式调用不生效

(new Dog)->feeding('骨头')->hobby(',可爱,温顺,听话~~');

以上就是php中的接口interface的详细内容,更多请关注搞代码gaodaima其它相关文章!


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

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

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

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

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