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).
__construct in interface
Moderator: General Moderators
Re: __construct in 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).
Code: Select all
<?php
$mysql = new MySQL();
$mysql->Connect(/* Data */);
$mysql->Ping($mysql->name->GetTables()['id']->title);
$mysql->Close();
?>Code: Select all
<?php
class APNav implements IData
{
$config;
public function __construct(&$conf)
{
$this->config = &$conf;
}
public function Create(/* ... */) {}
};
?>Re: __construct in interface
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).
- Christopher
- Site Administrator
- Posts: 13596
- Joined: Wed Aug 25, 2004 7:54 pm
- Location: New York, NY, US
Re: __construct in interface
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.
(#10850)
Re: __construct in interface
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.
What you're actually wanting is an Abstract class, because you are expecting an implementation (i.e. a DB connection)
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();