"user", " /> "user", " /> "user", "/>

Is there a way to get the predefined constants as name, not its value?

35 Views Asked by At

I am writing a code to generate dynamic prepared queries in PDO.

I have created an array that represents any table:

$tableUser=array(
    "name"=>"user",
    "columns"=>array(
        array("name"=>"user_id", "type"=>PDO::PARAM_INT),
        array("name"=>"user_name", "type"=>PDO::PARAM_STR),
        array("name"=>"user_lastname", "type"=>PDO::PARAM_STR),
    ),
);

I want to obtain an array with the columns and another array with the data types to use them later in the preparation of the query and for the bindParam.

This is my code:

$columns= array_column($tableUser["columns"], 'name');
$types= array_column($tableUser["columns"], 'type');

var_dump($columns);
var_dump($types);

Output:

array(3) {
  [0]=>
  string(7) "user_id"
  [1]=>
  string(9) "user_name"
  [2]=>
  string(13) "user_lastname"
}

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(2)
}

As you can see, the second var_dump shows me the values, not the names of the predefined constants.

Is there a way to get the names of the constants instead of the values? It's more out of curiosity and/or for clarity in the code, because I suppose that if I pass the values it will work correctly.

1

There are 1 best solutions below

0
lukas.j On

You could try with reflection:

$pdoParamConstants =
  array_flip(
    array_filter(
      ( new ReflectionClass(PDO::class) )->getConstants(ReflectionClassConstant::IS_PUBLIC),
      static function (int $value, string $key): bool {
        return str_starts_with($key, 'PARAM_')
          && $value < 6
          && $value !== 4
          && !str_starts_with($key, 'PARAM_EVT');
      },
      ARRAY_FILTER_USE_BOTH
    )
  );

With that we have an array which can be used as a lookup table:

echo $pdoParamConstants[yourValueHere];

For example:

echo $pdoParamConstants[PDO::PARAM_STR];   // Output: 'PARAM_STR'
echo $pdoParamConstants[PDO::PARAM_INT];   // Output: 'PARAM_INT'

getConstants will return all constants (in this case we want only public constants, hence the argument to it). Then we have to filter out all non data type constants. And because the returned array is in the form of constantName => constantValue, we flip it, to get the lookup table.

Note that this does not work so simple if one of the following constants comes into play: PARAM_STR_NATL, PARAM_LOB and PARAM_INPUT_OUTPUT.