Page 1 of 1

__construct in interface

Posted: Sun May 10, 2009 11:59 am
by koen.h
Any reasons why one shouldn't, as a general rule, put __construct() in an interface?

A reason why I would put it in there is the be certain (per interface contract) an object has all the dependencies it needs to operate (eg a database connection).

Re: __construct in interface

Posted: Sun May 10, 2009 12:07 pm
by Defiline
A reason why I would put it in there is the be certain (per interface contract) an object has all the dependencies it needs to operate (eg a database connection).

Code: Select all

<?php
 
$mysql = new MySQL();
 
$mysql->Connect(/* Data */);
$mysql->Ping($mysql->name->GetTables()['id']->title);
$mysql->Close();
 
?>
In my case I am using __construct(ors) to pass all configuration and language preferences:

Code: Select all

<?php
 
class APNav implements IData
{
    $config;
 
    public function __construct(&$conf)
    {
        $this->config = &$conf;
    }
 
    public function Create(/* ... */) {}
};
 
?>

Re: __construct in interface

Posted: Sun May 10, 2009 12:13 pm
by koen.h
An argument against using __construct in your implementing classes only is, imo, that the client classes are tied not to the interface but to the specific class they use (because they have to know from the specific class what it needs to work).

Re: __construct in interface

Posted: Sun May 10, 2009 2:35 pm
by Christopher
The reason to put anything in an interface is to enforce that it is there in the implementation. So if the constructor need to be enforced then is should be in the interface; if not then no.

Re: __construct in interface

Posted: Sun May 10, 2009 8:23 pm
by Jenk
A constructor has no need to be in an interface, because in order to construct the object from the class, you *must* have the class information already.. ergo, you're already using the concrete class anyway. You cannot, and should not, be obliging a subclass to its implementation, only its interface.

Code: Select all

interface IFoo {
  function foo();
}
 
class Foo implements IFoo {
  function __construct($blah) {}
  function foo() {}
}
 
$foo = (IFoo)new Foo(); // this is not new IFoo();
What you're actually wanting is an Abstract class, because you are expecting an implementation (i.e. a DB connection)