4

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();
?>
gfr
  • 41
  • 1
  • 2
  • At a guess I'd say because all methods within an interface are abstract, that's what interfaces are, collections of abstract methods. – user229044 Sep 11 '10 at 22:21

3 Answers3

17

All functions in an interface are implicitly abstract. There is no need to use the abstract keyword when declaring the function.

Vincent Ramdhanie
  • 102,349
  • 23
  • 137
  • 192
7

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.

EricBoersma
  • 1,019
  • 1
  • 8
  • 19
  • This should be the accepted answer. Although, aside from abstract methods allowing to have visibility other than public, are there any differences between a public abstract method and a public method in an interface? – Katrina Jan 22 '18 at 17:33
1

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.

user3805033
  • 157
  • 1
  • 3