__construct in interface

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
koen.h
Forum Contributor
Posts: 268
Joined: Sat May 03, 2008 8:43 am

__construct in interface

Post 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).
Defiline
Forum Commoner
Posts: 59
Joined: Tue May 05, 2009 5:34 pm

Re: __construct in interface

Post 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(/* ... */) {}
};
 
?>
koen.h
Forum Contributor
Posts: 268
Joined: Sat May 03, 2008 8:43 am

Re: __construct in interface

Post 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).
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: __construct in interface

Post 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.
(#10850)
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Re: __construct in interface

Post 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)
Post Reply