Intermediate LevelPHP 8+
How do you customize JSON output formatting for domain objects by implementing the JsonSerializable interface?
❓ Interview Prompt: Explain the JsonSerializable interface, jsonSerialize() method, and controlling json_encode() serialization output.
By default, passing an object to 'json_encode($obj)' serializes only its public properties. Private and protected properties are omitted.
'JsonSerializable' Interface:
Implementing the 'JsonSerializable' interface requires defining a 'jsonSerialize()' method. This method controls the exact array representation exported whenever 'json_encode()' is invoked on your object, allowing you to sanitize sensitive passwords or format custom JSON field names!
Code Implementation Example
php
<?php
class UserDTO implements JsonSerializable {
public function __construct(
private int $id,
private string $name,
private string $hashedPassword // Sensitive data!
) {}
// Custom JSON serialization representation
public function jsonSerialize(): mixed {
return [
'id' => $this->id,
'name' => $this->name
// hashedPassword is safely excluded!
];
}
}
echo json_encode(new UserDTO(42, 'Alice', 'secret_hash'));
// Outputs: {"id":42,"name":"Alice"}💡Sanitizing private object attributes during json_encode using JsonSerializable.
🎯 Interview Key Takeaway
Implement JsonSerializable and define jsonSerialize() to customize JSON output and exclude sensitive properties.
#JsonSerializable#JSON#OOP#Intermediate
Back to all PHP 8+ Questions→