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();
An interface can contain methods and constants, but can't contain any variables.
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.
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.
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.
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
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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With