我有一个函数,它有以下头部(简单pdo包装类的一部分):
function select($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("User", $where);
或
$dbpdo->select("User", $fields, $where);
您可以使用func_get_args()
和func_num_args()
以不同的方式处理对函数的两个参数和三个参数调用,但我不建议这样做,因为这会使您的函数可能会让其他人感到困惑。
就我个人而言,我认为$dbpdo->select("User", [], $where);
还可以。
如果$fields更有可能具有默认值/空值,您也可以考虑交换$where和$fields参数。