Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

561
Vistas
PHP Enums `__toString` magic method

I am wondering why it is not possible to provide an __toString implementation for enum.

IDE says "Enum may not include '__toString'". However it was the first thing I thought about once I created enum. Previously I used Value Objects encapsulating strings in my code, which utilized string casting when necessary. Now I would like to migrate 'em into enums, but those resist.

#[Immutable]
enum SaveKlinesFromApiQueue: string
{
    case DEFAULT = 'save_klines_from_api_queue';
    case PRIORITY = 'save_klines_from_api_priority_queue';

    public function __toString(): string
    {
        return $this->value;
    }
}
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

As chris mentions, magic methods are not allowed.

For the 2 most(?) common usecases:

To get the string value of a single one, you can just use ->value.

If you want the string values of all of them, just add a loop in a method:

    public static function strings(): array
    {
        $strings = [];
        foreach(self::cases() as $case) {
            $strings[] = $case->value;
        }
        return $strings;
    }
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda