Forum Moderators: coopster

Message Too Old, No Replies

Function declaration with optional parameters

Can't find out how to get the optional prarameters into my functions

         

John_Keates

3:05 pm on Mar 26, 2006 (gmt 0)

10+ Year Member



Hi,
I'm making some functions for a mysql based photo album system.
Now I want a function with optional parameters so I can just put one in and don't see any error because the others wheren't filled out.

function photo_getpid($file, $album, $oid, $x, $y){
//some code to find out what's used and to set the query
return $ret_var;
};

I've seen some things where & was put in front of a argument and where arguments where given a value like you do with variables. I still can't find out what's needed to make arguments optional..

DrDoc

4:16 pm on Mar 26, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



There are multiple ways of acheiving this, depending on your needs.

Here are a few helpful pages from php.net:
Function arguments [php.net]
func_get_args() [php.net], for variable length argument lists
References [php.net], which is what you were talking about when mentioning the ampersand.

I'd look at all three, though, as they provide different flexibility depending on usage and needs.

dreamcatcher

4:21 pm on Mar 26, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



To create variables as optional, you can set an initial value:

function photo_getpid($file='', $album='', $oid='', $x='', $y='')

In this case each variable has been assigned, so just using:

photo_getpid();

will be ok with no errors.

So, assign the variables, then check in the function if any have values.

dc

DrDoc

4:24 pm on Mar 26, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Just remember that if you preset your variables and later want to pass a non-default value, they have to be supplied in order. You cannot omit the first if you only want to pass $x. Using variable length argument lists you can, however.

John_Keates

4:32 pm on Mar 26, 2006 (gmt 0)

10+ Year Member



Thanks, I did look at those pages before, but I didn't know the solution was on the 1st one at the bottem: Example 17-10.
dreamcatcher just explained what I wanted to do, thanks.
DrDoc thank you for explainin the way to not assign the predefined arguments and only have one position filled while others left open.

My problem is solved, Thanks