PHP:使用可能有参数或没有参数的方法

标签 php methods

我的类中有一个查询数据库的函数。我使用基于变量的 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/

相关文章:

php - 如何使用symfony2学说在表中添加列

PHP : I need to fill "0" on months where there is no data available from a sql query

java - 在一个变量中引用方法的参数

php - 防止用户使用一个电子邮件地址创建多个帐户?

php - 如何在 Doctrine2 (Symfony2) 中按案例排序

PHP 输出缓冲区不刷新

java - 调用方法时将数组初始化为参数

c++ - 应该使用什么优雅的方法回调设计?

java - 是否可以反转子字符串的起点和终点?

iphone - 如何使 NSObject "global"/在所有方法中可用?