开发者

PHP: using a method that may or may not have parameters

I have a function in a class that queries a database. I create the query on the fly by using where clauses based on variables.

Say I have a method like this:

function getBackups($from, $to, $clientid){

    //sql here
    //add where clause if $from and $to not null...

}

If I want to call this somewhere In a situation where I have no from or to variables I would simply put $backups->getBackups() but I'd get an error about a missing parameter.

If I do this:

function getBackups($from = null, $to = null开发者_如何学JAVA, $clientid = null){

    //sql here
    //add where clause if $from and $to not null...
}

Will this be the solution? or will it be more like this if I'm not passing parameters?

$backups->getBackups($from = null, $to = null, clientid = null)

Hope this makes sense,

Jonesy


you can do what you say:

function getBackups($from = null, $to = null, $clientid = null){

    //sql here
    //add where clause if $from and $to not null...
}

an then you can call it just like:

$backups->getBackups()

or you can call

$backups->getBackups($from, $to, $clientid)

Inside the function you can check if the aprameters are null (or any other default value you like to use) and execute the code depending of the parameters.

HTH regards.


function getBackups($from = null, $to = null, $clientid = null){

    //sql here
    //add where clause if $from and $to not null...
}

Is the solution for functions with optional parameters, if that is what you mean.


optional parameters in php is as simple as this:

function getBackups($from = null, $to = null, $clientid = null){

    //sql here
    //add where clause if $from and $to not null...
}

And to call it, you just call:

backups->getBackups();

or

backups->getBackups("from");

if you include any arguments to the function, they will replace the default values in the order they appear.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜