Since PHP 8.6, the __debugInfo magic method can be defined on enums. It returns an array, which is used by the functions that output debug information about a value, such as var_dump and print_r. Before PHP 8.6, enums were not allowed to define this method, and such code failed with a fatal error.
The following enum defines the __debugInfo method, which returns the name and the value of a case under custom keys:
UserStatus.php
<?php
enum UserStatus: string
{
case ACTIVE = 'A';
case BLOCKED = 'B';
public function __debugInfo(): array
{
return [
'status' => $this->name,
'symbol' => $this->value,
];
}
}
<?php
require_once 'UserStatus.php';
var_dump(UserStatus::ACTIVE);
Output:
enum(UserStatus::ACTIVE) (2) {
["status"]=>
string(6) "ACTIVE"
["symbol"]=>
string(1) "A"
}
Without the __debugInfo method, the var_dump function prints only the enum and the case name:
enum(UserStatus::ACTIVE)
The enum(UserStatus::ACTIVE) part is always printed, so the method cannot hide which case is dumped.
Leave a Comment
Cancel reply