0

Possible Duplicate:
Can I use a function to return a default param in php?
Using function result as a default argument in PHP function

I am trying to set default value for a function. I want the function $expires default value to be time() + 604800.

I am trying

public function set($name,$value,$expires = time()+604800) {
    echo $expires;
    return setcookie($name, $value, $expires);
    }

But I get an error.

Parse error: syntax error, unexpected '(', expecting ')' in /var/www/running/8ima/lib/cookies.lib.php on line 38

How should I write it?

1
  • Wouldn't if (!$expires) { $expires = time() + 604800; } do it ?
    – user625860
    Commented Mar 1, 2012 at 9:37

4 Answers 4

4
$expires = time()+604800

in the function definition.

Default value can't be the result of a function, only a simple value QUoting from the manual:

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

Use:

public function set($name,$value,$expires = NULL) { 
    if (is_null($expires))
        $expires = time()+604800;
    echo $expires; 
    return setcookie($name, $value, $expires); 
} 
1
  • 3
    +1 first answer that actually explains what's wrong. Commented Mar 1, 2012 at 9:38
1

You cannot use a function call in your params declaration.

Do it this way:

public function set($name,$value,$expires = null) {
    if(is_null($expires)) $expires = time()+604800;
    echo $expires;
    return setcookie($name, $value, $expires);
}
0

try this:

public function set($name,$value,$expires = NULL) {
    if(is_null($expires)) {
        $expires = time() + 604800;
    }
    echo $expires;
    return setcookie($name, $value, $expires);
}
1
  • +1 if you can also explain why. Commented Mar 1, 2012 at 9:37
0

You could do

public function set($name,$value,$expires = null) {
 if($expires === null){$expires = time()+604800);
 echo $expires;
 return setcookie($name, $value, $expires);
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.