phpinterface

PHP: Can I Use Fields In Interfaces?


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();

Solution

  • You cannot specify members before PHP 8.4.0. You'd 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();
    }
    

    As of PHP 8.4.0, interfaces may also declare properties. If they do, the declaration must specify if the property is to be readable, writeable, or both. The interface declaration applies only to public read and write access:

    interface I
    {
        // An implementing class MUST have a publicly-readable property,
        // but whether or not it's publicly settable is unrestricted.
        public string $readable { get; }
    
        // An implementing class MUST have a publicly-writeable property,
        // but whether or not it's publicly readable is unrestricted.
        public string $writeable { set; }
    
        // An implementing class MUST have a property that is both publicly
        // readable and publicly writeable.
        public string $both { get; set; }
    }
    

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