Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up

Explain object-oriented programming in PHP: interfaces, abstract classes and traits.

PHP gives you three ways to share structure, and the interview question is usually about choosing between them.

  • Interface — a contract of method signatures with no implementation. A class may implement many. Use it to say what a class can do, so unrelated classes can be used interchangeably.
  • Abstract class — a partial implementation that cannot be instantiated. It may hold state, constructors, and concrete methods alongside abstract ones. A class may extend only one. Use it for an "is-a" relationship where subclasses genuinely share behaviour.
  • Trait — a block of methods copied into a class at compile time. It is PHP's answer to the lack of multiple inheritance. Use it for behaviour reused across classes with no natural common ancestor — a logging helper, a timestamp helper.

How to choose: prefer an interface for the contract and a trait for shared implementation, and reach for an abstract class when there is a real hierarchy. "Program to an interface" is what makes code testable, because you can substitute a fake.

Note: Traits have a real cost — they hide dependencies, since a trait method may rely on a property the using class must provide. Overusing them produces classes whose behaviour is scattered across five files.

All Php interview questions

Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up as