Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

564
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!