Can interface contain variables php?
In PHP, can I specify an interface to have fields, or are PHP interfaces limited to functions? Show
If not, I realize I can expose a getter as a function in the interface:
asked Feb 12, 2010 at 11:52
2 You cannot specify members. You have to indicate their presence through getters and setters, just like you did. However, you can specify constants:
See http://www.php.net/manual/en/language.oop5.interfaces.php answered Feb 12, 2010 at 12:03
GordonGordon 308k72 gold badges527 silver badges552 bronze badges 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:
While you could still have the interface:
Then you have your child class like this:
There's an alternative solution for those still curious and interested. :) answered May 11, 2013 at 3:48
WIMP_noWIMP_no 5095 silver badges7 bronze badges 4 Use getter setter. But this might be tedious to implement many getters and setters in many classes, and it clutter class code. And you repeat yourself! As of PHP 5.4 you can use traits to provide fields and methods to classes, ie:
This is specially usefull if you have to inherit from some base class and need to implement some interface.
answered Apr 18, 2014 at 14:01 1 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. answered Feb 12, 2010 at 11:54
Noah GoodrichNoah Goodrich 24.5k13 gold badges65 silver badges95 bronze badges You cannot specify properties in an
Will give you :
answered Feb 12, 2010 at 11:56
Pascal MARTINPascal MARTIN 389k77 gold badges647 silver badges656 bronze badges CAN interface have variables in PHP?An interface can contain methods and constants, but can't contain any variables.
Can an interface contain variables?Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, no body). Interfaces specify what a class must do and not how.
CAN interface have properties in PHP?Interfaces cannot have properties, while abstract classes can. All interface methods must be public, while abstract class methods is public or protected. All methods in an interface are abstract, so they cannot be implemented in code and the abstract keyword is not necessary.
What is the advantage of using interface in PHP?Advantages of PHP Interface
An interface allows unrelated classes to implement the same set of methods, regardless of their positions in the class inheritance hierarchy. An interface can model multiple inheritances because a class can implement more than one interface whereas it can extend only one class.
|