Skip to content

11: Customize Enum Dumps with __debugInfo()

Show a human-readable status and an enum’s machine value when inspecting it with var_dump().

  • PHP 8.6 CLI. Confirm the version with php --version.
  • Review the previous chapter if you’re following the series in order.

Allow about 10 minutes for the walkthrough and exercise.

A runnable enum-debug-info.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/11-enum-debug-info/enum-debug-info.php
enum-debug-info.php
<?php
declare(strict_types=1);
enum JobState: string
{
case Queued = 'queued';
case Complete = 'complete';
public function __debugInfo(): array
{
return ['state' => $this->value, 'finished' => $this === self::Complete];
}
}
var_dump(JobState::Queued);
echo json_encode(JobState::Queued, JSON_THROW_ON_ERROR), PHP_EOL;
enum(JobState::Queued) (2) {
["state"]=>
string(6) "queued"
["finished"]=>
bool(false)
}
"queued"

PHP calls __debugInfo() to obtain the fields shown by var_dump(). The method returns an array. Backed values and enum identity are unaffected by the debug view.

Add a Failed case and include a retryable field that is true only for that case. Dump both cases and compare the field.

Continue with Change Properties on Objects Held in Constants.