PHP:接口中的抽象方法
为什么我不能在接口中声明抽象方法?这是我的代码。谢谢。
<?php
interface Connection {
public abstract function connect();
public function getConnection();
}
abstract class ConnectionAbstract implements Connection() {
private $connection;
public abstract function connect();
public function getConnection() {
return $this->connection;
}
}
class MySQLConnection extends ConnectionAbstract {
public function connect() {
echo 'connecting ...';
}
}
$c = new MySQLConnection();
?>
why cannot I declare an abstract method within an interface? This is my code. Thank you.
<?php
interface Connection {
public abstract function connect();
public function getConnection();
}
abstract class ConnectionAbstract implements Connection() {
private $connection;
public abstract function connect();
public function getConnection() {
return $this->connection;
}
}
class MySQLConnection extends ConnectionAbstract {
public function connect() {
echo 'connecting ...';
}
}
$c = new MySQLConnection();
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
接口中的所有函数都是隐式抽象的。声明函数时不需要使用abstract关键字。
All functions in an interface are implicitly abstract. There is no need to use the abstract keyword when declaring the function.
请记住,实现接口的类必须包含一系列与接口中声明的方法签名相对应的公共方法。因此,例如,当您声明一个已定义公共抽象函数的接口时,您实际上是在说每个实现该接口的类都必须有一个名为 connect 的公共抽象方法代码>.由于具有抽象方法的对象无法实例化,因此您最终将编写一个永远无法使用的接口。
Remember that the requirement of a class which implements an interface must contain a series of public methods which correspond to the method signatures declared in the interface. So, for instance, when you declare an interface which has a defined
public abstract function
, you're literally saying that every class which implements the interface must have a public abstract method namedconnect
. Since objects with abstract methods cannot be instantiated, you'll end up writing an interface which can never be used.Connection 接口中的两个方法都是抽象的。接口中的所有方法都是隐式抽象的。因此 connect() 方法不需要抽象关键字。
Both the methods in the Connection interface are abstract. All methods in an interface are implicitly abstract. So abstract keyword is not required for the connect() method.