$headers Key-value pairs of additional HTTP headers */ public function __construct( public readonly int $statusCode, public readonly string $contentType, public readonly string $body, public readonly array $headers = [], ) {} public function __toString(): string { $reason = match ($this->statusCode) { 200 => 'OK', 400 => 'Bad Request', 401 => 'Unauthorized', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 500 => 'Internal Server Error', default => '', }; $statusLine = trim("HTTP/1.1 {$this->statusCode} {$reason}"); $contentLength = strlen($this->body); // Build base headers. $formattedHeaders = [ $statusLine, "Content-Type: $this->contentType", "Content-Length: $contentLength", "Connection: close", ]; // Format and append custom headers. foreach ($this->headers as $name => $value) { $formattedHeaders[] = "$name: $value"; } return implode("\r\n", $formattedHeaders) . "\r\n\r\n" . $this->body; } }