Do PHP interfaces have properties?

Does an interface in PHP have properties, or do they only have methods?

+44
methods oop php interface
May 03 '10 at 8:49
source share
4 answers

It depends on what you mean by "properties." If you mean actual fields, then no, they do not. If you refer to properties such as C #, then yes, they can (since property accessors are strictly syntactic sugar for access methods anyway). The same applies to events (although, of course, in each case the implementation does not apply to get / set or add / remove accessories).

Refresh . Since PHP has no properties in the sense of get / set accessories, then the answer to your question is no. Interfaces cannot carry their own data / state.

+25
May 03 '10 at 8:52 a.m.
source share

Interfaces in PHP can only contain a publicly signed method without a method body. They may also contain constants. But it is so. Nothing more.

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

Interfaces are defined using the interface keyword in the same way as the standard class, but without any methods defining their contents. [...] All methods declared in the interface must be publicly available, this is the nature of the interface. [...] Its capabilities for interfaces to have constants. Interface constants work just like class constants, except that they cannot be overridden by the class / interface that inherits it.

+14
May 03 '10 at 8:59
source share

PHP interfaces can have constants, but not properties (instance variables). If you do not need to change your property, you can use a constant instead.

+9
May 03 '10 at 8:58 a.m.
source share

The [real] reason for using properties in an interface is to indicate that the DTO class has a certain aspect, for example. IOrderable {OrderDate, OrderStatus}, IDeliverable {DeliveryAddress, Route, ...} etc. Aspect can be used in a number of DTOs, for example. Sales Order, Work Order, Invoices, etc. A DTO class can support several aspects, that is, multiple inheritance, which is desirable in data classes (but not in class classes). After that, the DTO client is sure that he can view the DTO through this aspect (interface contract). This template complies with all 5 SOLID principles.

In PHP, the closest to interface properties are the features of http://php.net/manual/en/language.oop5.traits.php . Like interfaces, features cannot be created, but they can be used directly in classes without their implementation.

-one
03 Oct '17 at 11:39 on
source share



All Articles