4

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

3 Answers 3

17

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

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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?
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.

1 Comment

How is this different from the first answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.