Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Can I Use Fields In Interfaces?

Tags:

php

interface

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(); 
like image 565
Doctor Blue Avatar asked Feb 12 '10 11:02

Doctor Blue


People also ask

CAN interface have variables in PHP?

An interface can contain methods and constants, but can't contain any variables.

CAN interface have properties in PHP?

PHP - Interfaces vs.Interfaces cannot have properties, while abstract classes can. All interface methods must be public, while abstract class methods is public or protected.

Does PHP support interface?

A PHP interface defines a contract which a class must fulfill. If a PHP class is a blueprint for objects, an interface is a blueprint for classes. Any class implementing a given interface can be expected to have the same behavior in terms of what can be called, how it can be called, and what will be returned.

Can PHP implement multiple interfaces?

Yes, more than two interfaces can be implemented by a single class. From the PHP manual: Classes may implement more than one interface if desired by separating each interface with a comma.


2 Answers

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

like image 149
Gordon Avatar answered Sep 29 '22 08:09

Gordon


Late answer, but to get the functionality wanted here, you might want to consider an abstract class containing your fields. The abstract class would look like this:

abstract class Foo {     public $member; } 

While you could still have the interface:

interface IFoo {     public function someFunction(); } 

Then you have your child class like this:

class bar extends Foo implements IFoo {     public function __construct($memberValue = "")     {         // Set the value of the member from the abstract class         $this->member = $memberValue;     }      public function someFunction()     {         // Echo the member from the abstract class         echo $this->member;     } } 

There's an alternative solution for those still curious and interested. :)

like image 30
WIMP_no Avatar answered Sep 29 '22 08:09

WIMP_no