我的类中有一个查询数据库的函数。我使用基于变量的 where 子句动态创建查询。
假设我有这样的方法:
function getBackups($from, $to, $clientid){
//sql here
//add where clause if $from and $to not null...
}
如果我想在某个地方调用它,在没有 from 或 to 变量的情况下,我只需放置 $backups->getBackups() ,但我会收到有关缺少参数的错误。
如果我这样做:
function getBackups($from = null, $to = null, $clientid = null){
//sql here
//add where clause if $from and $to not null...
}
这会是解决方案吗?或者如果我不传递参数,它会更像这样吗?
$backups->getBackups($from = null, $to = null, clientid = null)
希望这是有道理的,
琼斯
最佳答案
你可以按照你所说的去做:
function getBackups($from = null, $to = null, $clientid = null){
//sql here
//add where clause if $from and $to not null...
}
然后你可以像这样调用它:
$backups->getBackups()
或者您可以调用
$backups->getBackups($from, $to, $clientid)
在函数内部,您可以检查参数是否为空(或您喜欢使用的任何其他默认值)并根据参数执行代码。
HTH 致以问候。
关于PHP:使用可能有参数或没有参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4247309/