Objects bundle data and behavior. PHP supports classes, interfaces, traits, enums (PHP 8.1+), and readonly properties (PHP 8.2+).
Basic class
class User {
public function __construct(
public string $name,
public string $email,
) {}
public function label(): string {
return $this->name;
}
}
$u = new User('Ada', 'ada@example.com');
Constructor property promotion
PHP 8 shorthand declares and assigns properties in the constructor parameter list—common in DTOs and value objects.
$this
Inside instance methods, $this refers to the current object. Static methods use self:: or static::.
Important interview questions and answers
- Q: Class vs object?
A: Class is the blueprint; object is an instance created withnew. - Q: When use readonly properties?
A: Immutable value objects initialized once in the constructor—PHP 8.2+.
Self-check
- What keyword creates an instance?
- What does constructor promotion save you from writing?
Tip: Constructor property promotion (PHP 8) keeps DTOs short—pair with readonly properties when values must not change.
Interview prep
- Constructor promotion?
PHP 8 lets you declare constructor parameters with visibility modifiers—they become properties automatically, reducing boilerplate in DTOs.