Reputation: 41
Why cannot I declare an abstract method within an interface?
<?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();
?>
Upvotes: 4
Views: 7855
Reputation: 157
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.
Upvotes: 1
Reputation: 1019
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 named connect
. Since objects with abstract methods cannot be instantiated, you'll end up writing an interface which can never be used.
Upvotes: 7
Reputation: 103145
All functions in an interface are implicitly abstract. There is no need to use the abstract keyword when declaring the function.
Upvotes: 17