我有一个具有以下 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/