I would like to applay array_values( $array_of_enums )
on array of enums but I got this error :
Object of class XXXX could not be converted to string in ...
So I wander how to get easily enum values store in an array and NOT all values existing for an enum.
CodePudding user response:
If you are working with an object that represents an enum, you can use the get_object_vars function to extract its properties (which represent the enum values) into an array.
Here's an example:
class MyEnum {
const ENUM_VALUE_1 = 1;
const ENUM_VALUE_2 = 2;
const ENUM_VALUE_3 = 3;
}
$enum = new MyEnum();
$enum_values = array_values(get_object_vars($enum));
print_r($enum_values);
This will output:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
CodePudding user response:
For the moment I create this function :
/**
* @param UnitEnum[] $array_of_enums
* @return array|false
* @throws JsonException
*/
function array_enum_values( array $array_of_enums ){
$output = [];
foreach ( $array_of_enums as $enum ){
if( !$enum instanceof \UnitEnum ){
error_log( sprintf( "array_enum_values() cannot be executed correctly, one value is not an enum : %s", json_encode( $enum, JSON_THROW_ON_ERROR ) ) );
return false;
}else{
$output[] = $enum->value;
}
}
return $output;
}