Passing Optional Arguments

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
snowrhythm
Forum Commoner
Posts: 75
Joined: Thu May 04, 2006 1:14 pm
Location: North Bay Area, CA

Passing Optional Arguments

Post by snowrhythm »

I'm sure everyone knows about functions that you can pass 'optional' arguments to, I was just wondering if there is any special syntax for creating a function myself that can work that way. That is, a function where some parameters are necessary and some are optional. Thanks.
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

Assign false to it and then give it a default in your function

Code: Select all

function this_has_optional_params($required, $optional=false){
    if(!$optional) $optional = 'default_value';
    // Do stuff
}
OR just give it the default right away

Code: Select all

function this_has_optional_params($required, $optional='default_value'){
    // Do stuff
}
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Code: Select all

function foobar($optional = '') 
{
   return var_dump($option);
}

echo foobar() .'<br />';
echo foobar('hi');
:wink:
User avatar
snowrhythm
Forum Commoner
Posts: 75
Joined: Thu May 04, 2006 1:14 pm
Location: North Bay Area, CA

Post by snowrhythm »

Thanks guys...I appreciate the help.
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

For clarity you may want to default to the same type as what is expected to be passed to it.

Code: Select all

<?php
function my_function($int = 0, $str = '', $bool = false)
{
    // yaddah yaddah
}
?>
Post Reply