提问人:robinb96 提问时间:10/19/2023 最后编辑:robinb96 更新时间:10/20/2023 访问量:38
如何在PHP中为函数参数设置预定义选项?[复制]
How to set predefined options for a function parameter in PHP? [duplicate]
问:
我想知道是否可以在 PHP8 中为函数参数设置预定义选项。我只能找到设置默认选项,但这不是我要找的。我有一个简单的用例如下。
function runQuery($query, $values = NULL, $returnValue = NULL){
if ($returnValue == 'numRows'){
//query will run here and return the number of rows that are selected
} elseif ($returnValue == 'getAffectedRows'){
//query will run here and return the number of affected rows (for example to check if a create, update or delete is succesfull)
} elseif ($returnValue == 'getLastInsertID'){
// query will run and return the ID of the inserted row
} else {
// query will execute without any returns
}
}
现在,在编写代码时,在输入字符串作为 returnValue 时很容易出错。例如,当不使用大写字母或只是拼写错误时。此外,IDE 无法识别选项是什么。这也会在重构时产生很多错误。
我有一个以如下方式调用returnValue选项的想法,但真的不知道如何实现它。或者如果可能的话。(大多数IDE都能够在这里找到可能性,例如使用函数或实例的变量调用类的任何实例)
runQuery('SELECT * FROM table WHERE ID = ?', 5, $this->returnValue()->numRows());
我的另一个想法如下,但如果这样的事情可能的话,也没有找到任何信息。
function runQuery($query, $values=NULL, $returnValue = ('numRows' || 'getAffectedRows' || 'getLastInsertID' || 'none')){
//same code here as in first code snippet
}
如果有人可以帮忙,欢迎你!还有关于如何解决这个问题的想法,着眼于代码的可维护性。特别是当代码库变得很大并且您需要更改像这样设置的函数时,而它们在整个代码库的许多地方都使用。
答: 暂无答案
上一个:php 如果调整图像大小添加水印
下一个:简单产品 - 显示属性下拉列表
评论
returnValues
runQuery
returnValues $returnValue
match($returnValue){ returnValues::numRows => numRows(), and so on }
swtich($returnValue){...}
if($returnValue == returnValues::numRows){...}