如何在PHP中为函数参数设置预定义选项?[复制]

How to set predefined options for a function parameter in PHP? [duplicate]

提问人:robinb96 提问时间:10/19/2023 最后编辑:robinb96 更新时间:10/20/2023 访问量:38

问:

我想知道是否可以在 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 函数 参数 传递

评论

0赞 shingo 10/19/2023
你知道枚举吗?
0赞 robinb96 10/19/2023
@shingo我没有。您能否详细说明一下如何处理它。现在我在类上方设置了一个枚举,称为 。在函数中,我有参数。然后,对于每个选项,在其中声明另一个函数。并以 .是否可以将函数放在匹配部分的某个位置,例如if-else的行为方式?非常感谢你为我指明了正确的方向!returnValuesrunQueryreturnValues $returnValuematch($returnValue){ returnValues::numRows => numRows(), and so on }
1赞 shingo 10/19/2023
您可以像往常一样使用语句或语句。swtich($returnValue){...}if($returnValue == returnValues::numRows){...}
0赞 Chris Haas 10/20/2023
下面是一个匹配版本:3v4l.org/3QetC#v8.2.11

答: 暂无答案