php - 在 php 函数中将多个数组作为可选参数的最佳方法

标签 php mysql pdo

我有一个具有以下 header 的函数(简单 pdo 包装器类的一部分):

函数选择($table_name, $fields = [], $where = [])

当我有一个 where 子句但我想为字段使用默认值时会变得很尴尬,就像这样的调用:

  $where = array(
    'Username'    =>  $username,
    'Password'    =>  $encrypted_password
  );

  // Select all fields from User with the where clause above
  $STMT = $dbpdo->select("User", [], $where);`

这只是一个例子来说明这个问题。在 php 中使用这种类型的结构最优雅的方法是什么?理想情况下,我想使用如下调用:

$dbpdo->select("用户", $where);

$dbpdo->select("用户", $fields, $where);

最佳答案

可以使用func_get_args()func_num_args() 以不同方式处理对函数的二参数和三参数调用,但我不推荐这样做,因为这会使您的函数可能会混淆其他人的使用。

我个人认为 $dbpdo->select("User", [], $where); 就好了。

您还可以考虑交换 $where 和 $fields 参数,如果 $fields 更有可能具有其默认/空值。

关于php - 在 php 函数中将多个数组作为可选参数的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34682631/

相关文章:

php - 从两个表中各选择一条记录。通过将另一个值与新表匹配来更新一个值

ubuntu中的php GD库错误

php - 使用 .htaccess 创建 SEO 网址

php - 电视节目数据库 : delete shows that has foreign key seasons

PHP - PDO - 如何只用一个查询获取多行?

php - 获取最后插入的 id 返回 null

php - 使用下拉菜单从 MySQL 提取和发布数据

mysql - Perl 模块 : MySQL vs DBI

php - 连接不同数据库上的表,同时绑定(bind)值

php - 无法让 PHP 类函数使用类中的另一个函数