php 一个类可以扩展一个类并实现一个接口吗

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/652157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:23:04  来源:igfitidea点击:

Can a class extend both a class and implement an Interface

phpphp-parse-error

提问by Pim Jager

Can a class extend both an interface and another class in PHP?
Basically I want to do this:

一个类可以在 PHP 中扩展一个接口和另一个类吗?
基本上我想这样做:

interface databaseInterface{
 public function query($q);
 public function escape($s);
 //more methods
}

class database{ //extends both mysqli and implements databaseInterface
 //etc.
}

How would one do this, simply doing:

如何做到这一点,只需这样做:

class database implements databaseInterface extends mysqli{ 

results in a fatal error:

导致致命错误:

Parse error: syntax error, unexpected T_EXTENDS, expecting '{' in *file* on line *line*

回答by Simon Lehmann

Try it the other way around:

反过来试试:

class database extends mysqli implements databaseInterface { ...}

This should work.

这应该有效。

回答by Micha? Rudnicki

Yes it can. You just need to retain the correct order.

是的,它可以。您只需要保留正确的顺序。

class database extends mysqli implements databaseInterface { ... }

Moreover, a class can implement more than one interface. Just separate 'em with commas.

而且,一个类可以实现多个接口。用逗号将它们分开。

However, I feel obliged to warn you that extending mysqli class is incredibly bad idea. Inheritance per se is probably the most overrated and misused concept in object oriented programming.

但是,我不得不警告您,扩展 mysqli 类是非常糟糕的主意。继承本身可能是面向对象编程中最被高估和滥用的概念。

Instead I'd advise doing db-related stuff the mysqli way (or PDO way).

相反,我建议以 mysqli 方式(或 PDO 方式)做与数据库相关的事情。

Plus, a minor thing, but naming conventions do matter. Your class databaseseems more general then mysqli, therefore it suggests that the latter inherits from databaseand not the way around.

另外,一件小事,但命名约定确实很重要。你的班级database似乎更一般mysqli,因此它表明后者继承自database而不是周围的方式。

回答by nullpointer

yes, in fact if you want to implement multiple interfaces you can do like this:

是的,事实上,如果你想实现多个接口,你可以这样做:

public class MyClass extends BaseClass implements myInterface1, myInterface2, myInterface3{ 

}