You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取PDO预定义常量的名称而非对应数值?

获取PDO预定义常量的名称

要获取PDO参数类型常量的名称而非数值,有两种实用方法可以实现:

1. 自定义映射数组

因为PDO的参数类型常量数量有限,手动创建数值与常量名称的映射表是最直接的方式,维护成本极低:

// 定义PDO参数类型的数值-名称映射
$pdoParamMap = [
    PDO::PARAM_INT => 'PDO::PARAM_INT',
    PDO::PARAM_STR => 'PDO::PARAM_STR',
    PDO::PARAM_BOOL => 'PDO::PARAM_BOOL',
    PDO::PARAM_NULL => 'PDO::PARAM_NULL',
    // 可根据需求补充其他类型
];

// 你的数据表定义数组
$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),
    ),
);

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

// 将数值转换为对应常量名称
$typeNames = array_map(function($type) use ($pdoParamMap) {
    return $pdoParamMap[$type] ?? '未知类型';
}, $types);

var_dump($columns);
var_dump($typeNames);

执行后$typeNames的输出为:

array(3) {
  [0]=>
  string(14) "PDO::PARAM_INT"
  [1]=>
  string(14) "PDO::PARAM_STR"
  [2]=>
  string(14) "PDO::PARAM_STR"
}

2. 利用反射自动提取常量

如果不想手动维护映射表,可以通过ReflectionClass自动获取PDO类中所有参数类型常量:

// 反射获取PDO类的所有常量,筛选出PARAM_开头的类型
$reflection = new ReflectionClass(PDO::class);
$pdoConstants = $reflection->getConstants();
$pdoParamMap = array_filter($pdoConstants, function($key) {
    return str_starts_with($key, 'PARAM_');
}, ARRAY_FILTER_USE_KEY);
// 反转数组,让数值作为键,常量名称作为值
$pdoParamMap = array_flip($pdoParamMap);

// 后续逻辑与第一种方法一致
$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),
    ),
);

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

$typeNames = array_map(function($type) use ($pdoParamMap) {
    return $pdoParamMap[$type] ?? '未知类型';
}, $types);

var_dump($columns);
var_dump($typeNames);

这种方法会自动同步PDO的所有PARAM_*类型常量,无需手动更新,适合需要兼容更多参数类型的场景。


内容的提问来源于stack exchange,提问作者A. Cedano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 20:12:18