gfr
gfr

Reputation: 41

PHP: Abstract method within an interface

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

Answers (3)

user3805033
user3805033

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

EricBoersma
EricBoersma

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

Vincent Ramdhanie
Vincent Ramdhanie

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

Related Questions