Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Abstract method within an interface

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();
?>
like image 687
gfr Avatar asked Nov 28 '22 19:11

gfr


2 Answers

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

like image 154
Vincent Ramdhanie Avatar answered Dec 05 '22 17:12

Vincent Ramdhanie


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.

like image 28
EricBoersma Avatar answered Dec 05 '22 17:12

EricBoersma