Jump to content

optional parameters


Branden Wagner

Recommended Posts

function optional arguements...
ok so... i looked on php.net and found that option parameters could be declared in functions like
function testing($var1, $var2 = 'test')
{
// your code
}

and this would make the $var2  optional.. but i cant get it to work on php5... am i doing something wrong.. or is there a different way to do it.
Link to comment
https://forums.phpfreaks.com/topic/27816-optional-parameters/
Share on other sites

What you mean that it doesn't work?  Some kind of error?  I'm using php 5.x (not sure of the exact version) and it works for me.

Try this on for size:
[code]
<?php
function test($v1, $v2 = "Blank"){
  echo "<br />This is V1:  " . $v1;
  echo "<br />This is V2:  " . $v2;
}

test("Test1");
test("Test1", "Test2");
?>
[/code]
Link to comment
https://forums.phpfreaks.com/topic/27816-optional-parameters/#findComment-127298
Share on other sites

I do believe THAT's what I did.  That's why I asked what made you think it didn't work.  Did you get some kind of error message?

The above code will display the following in the browser.

[quote]
This is V1:  Test1
This is V2:  Blank
This is V1:  Test1
This is V2:  Test2
[/quote]
Link to comment
https://forums.phpfreaks.com/topic/27816-optional-parameters/#findComment-127423
Share on other sites

yes but you dont have to place the blank in there, is all i am saying. otherwise your setting the default value to blank. it would be easier to set it as nothing, UNLESS you need a default value. depends on what the function is for i guess.
Link to comment
https://forums.phpfreaks.com/topic/27816-optional-parameters/#findComment-128420
Share on other sites

if you want a variable number of parameters

[code]
<?php

function foo () {

    $n = func_num_args();
    $sum = 0;
    for ($i=0; $i < $n; $i++) {
        $sum += func_get_arg($i);
    }
    return $sum;
}
?>
[/code]

echo foo (1,2,3);  // --> 6

echo foo (1,2,3,4,5);  // --> 15
Link to comment
https://forums.phpfreaks.com/topic/27816-optional-parameters/#findComment-129035
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.