tags:

views:

243

answers:

3

In PHP, can I specify an interface to have fields, or are PHP interfaces limited to functions?

<?php
interface IFoo
{
    public $field;
    public function DoSomething();
    public function DoSomethingElse();
}
?>

If not, I realize I can expose a getter as a function in the interface:

public GetField();
+2  A: 

Interfaces are only designed to support methods.

This is because interfaces exist to provide a public API that can then be accessed by other objects.

Publicly accessible properties would actually violate encapsulation of data within the class that implements the interface.

Noah Goodrich
+1  A: 

You cannot specify properties in an interface : only methods are allowed (and make sense, as the goal of an interface is to specify an API)


In PHP, trying to define properties in an interface should raise a Fatal Error : this portion of code :

interface A {
  public $test;
}

Will give you :

Fatal error: Interfaces may not include member variables in...
Pascal MARTIN
+3  A: 

You cannot specify members. You have to indicate their presence through getters and setters, just like you did. However, you can specify constants:

interface IFoo
{
    const foo = 'bar';    
    public function DoSomething();
}

See http://www.php.net/manual/en/language.oop5.interfaces.php

Gordon