Forum Moderators: coopster

Message Too Old, No Replies

Functions in custom function default arguments

         

zendak

2:04 pm on Mar 24, 2005 (gmt 0)

10+ Year Member



Sorry about the confusing subject line.
I've been looking around but couldn't find an answer to this.

Is it possible to pass a function to an argument variable of a custom function? i.e. something like this:


function getDateString($ts = time()) {
if (!isset($ts)) {
$ts = time();
}
return date('d.m.Y H:i:s', $ts);
}

If the function is called without an argument, it should default to the current timestamp. This throws a syntax error (expecting ')'), though.

Is it really only possible to pass a string or number as the default argument, instead of a function?

jamie

4:02 pm on Mar 24, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



hi,

can you not take out the time() call and simply pass $ts to the function, calling it like this if it has no value

$ts = 0;
getDateString($ts);

your function then looks like this

function getDateString($ts) {
if (!isset($ts)) {
$ts = time();
}
return date('d.m.Y H:i:s', $ts);
}

?

jollymcfats

4:41 pm on Mar 24, 2005 (gmt 0)

10+ Year Member



Expressions can not be used as default function arguments. You can often move the expression into the function to the same effect:

function getDateString($ts = null) {  
if ($ts == null)
$ts = time();
return date('d.m.Y H:i:s', $ts);
}

zendak

6:36 pm on Mar 24, 2005 (gmt 0)

10+ Year Member



Thank you, both solutions make sense. Assigning a NULL value to the default and then doing a check on that is what I need.