Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do PHP interfaces have properties?

Do interfaces in PHP have properties, or do they only have methods?

like image 452
never_had_a_name Avatar asked May 03 '10 08:05

never_had_a_name


People also ask

CAN interfaces contain properties?

Like a class, Interface can have methods, properties, events, and indexers as its members. But interfaces will contain only the declaration of the members. The implementation of the interface's members will be given by class who implements the interface implicitly or explicitly.

Should interfaces have properties?

Show activity on this post. Yes, An interface should define properties when it really in need.

CAN interfaces define properties?

An interface can contain declarations of methods, properties, indexers, and events. However, it cannot contain fields, auto-implemented properties.

Can PHP interface have variables?

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


2 Answers

It depends what you mean by "properties". If you mean actual fields, then no, they don't. If you're referring to properties such as those in C#, then yes they can (since the property accessors are strictly syntactic sugar for accessor methods anyway). The same goes for events (though of course, in each case, no implementation is specified for the get/set or add/remove accessors).

Update: Since PHP does not have properties in the sense of get/set accessors, then the answer to your question is no. Interfaces cannot carry their own data/state.

like image 83
Will Vousden Avatar answered Oct 07 '22 17:10

Will Vousden


You can declare properties in DocBlock for the interface. IDE's will then hint those properties for the interface (PhpStorm does) but this will not force the actual implementation of these fields in the implementing class. E. g.

/**  * @property string $password  * @property string $username  */ interface IUserDocument {   } 
like image 37
Josef Sábl Avatar answered Oct 07 '22 15:10

Josef Sábl