3v4l.org

run code in 300+ PHP versions simultaneously
<?php enum ProductCategories: string { case TSHIRT = 't_shirt'; case SHOES = 'shoes'; } abstract class Base { protected static array $categoryMappings; public static function getLocalCategoryId(ProductCategories $category): ?string { // Use $category->value to access the scalar value of the enum return static::$categoryMappings[$category->value] ?? null; } public static function getCategoryFromLocalId(string $categoryId): ?ProductCategories { // Flip the array to find the original enum based on categoryId $inverted = array_flip(static::$categoryMappings); if (array_key_exists($categoryId, $inverted)) { // Use ProductCategories::from to create enum from the string value return ProductCategories::from($inverted[$categoryId]); } return null; } abstract public function getByCategory(ProductCategories $category); } class A extends Base { protected static array $categoryMappings = [ ProductCategories::TSHIRT->value => '1', ProductCategories::SHOES->value => '2', ]; public function getByCategory(ProductCategories $category) { $localCategory = static::getLocalCategoryId($category); // Makes API call and returns results return $localCategory; } } class B extends Base { protected static array $categoryMappings = [ ProductCategories::TSHIRT->value => 't-shirt', ProductCategories::SHOES->value => 'mens-shoes', ]; public function getByCategory(ProductCategories $category) { $localCategory = static::getLocalCategoryId($category); // Makes API call and returns results return $localCategory; } } // Test cases echo A::getLocalCategoryId(ProductCategories::TSHIRT); // 1 echo "\n"; echo B::getLocalCategoryId(ProductCategories::TSHIRT); // t-shirt echo "\n"; echo A::getCategoryFromLocalId('1') === B::getCategoryFromLocalId('t-shirt') ? 'Same' : 'Not same'; echo "\n"; echo A::getLocalCategoryId(ProductCategories::SHOES); // 2 echo "\n"; echo B::getLocalCategoryId(ProductCategories::SHOES); // mens-shoes echo "\n"; echo "\n\n\n"; $aClass = new A(); echo $aClass->getByCategory(ProductCategories::TSHIRT); echo "\n"; $bClass = new B(); echo $bClass->getByCategory(ProductCategories::TSHIRT);
Output for 8.2.0 - 8.2.24, 8.3.0 - 8.3.12
1 t-shirt Same 2 mens-shoes 1 t-shirt
Output for 8.1.0 - 8.1.30
Fatal error: Constant expression contains invalid operations in /in/7umSN on line 37
Process exited with code 255.

preferences:
44.65 ms | 406 KiB | 5 Q