Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP naming conventions about abstract classes and interfaces

Should an abstract class always be prefixed with Abstract and suffixed with Interface (when it's an interface)? Is there any standard naming convention, similar to PSR-0 for folder structure/namespaces, but for classes?

It seems redundant as the language has literal keywords for this very purpose.

abstract class AbstractFoo {}

interface InterfaceFoo {}

trait TraitFoo {}
like image 402
gremo Avatar asked Nov 26 '12 11:11

gremo


People also ask

What is PHP naming convention?

Variable naming rules PHP First, every variable must start with the special character $ . Variables can then start with an underscore ( _ ) or any letter, but not with a number or a special character. The names of your variables cannot contain special characters such as & , % , # , or @ .

What is the difference between abstract class and interface in PHP?

The difference between interfaces and abstract classes are: Interfaces cannot have properties, while abstract classes can. All interface methods must be public, while abstract class methods is public or protected.

How do you name a class in PHP?

Class names should be descriptive nouns in PascalCase and as short as possible. Each word in the class name should start with a capital letter, without underscore delimiters. The class name should be prefixed with the name of the “parent set” (e.g. the name of the extension) if no namespaces are used.

How do you name an abstract class?

Abstract classes naming conventions I observed in many standard libraries, the naming conventions used for Abstract class is class name must start with Abstract or Base prefix. This naming convention can vary from organization to organization.


2 Answers

Although there's not any convention, I think it is a good practice using Abstract prefix and Interface suffix for respective components. It helps to understand better the code at a glance, IMO.

like image 199
Carlos Avatar answered Oct 10 '22 04:10

Carlos


The PHP-FIG project indeed suggests a naming convention via the PSR Naming Convention "ByLaw" https://www.php-fig.org/bylaws/psr-naming-conventions/

It states:

  • Interfaces MUST be suffixed by Interface: e.g. Psr\Foo\BarInterface

  • Abstract classes MUST be prefixed by Abstract: e.g. Psr\Foo\AbstractBar

  • Traits MUST be suffixed by Trait: e.g. Psr\Foo\BarTrait

These conventions are generally followed in packages

like image 32
wired00 Avatar answered Oct 10 '22 03:10

wired00