0

I was wondering if there is a simpler way that I can use a php inbuilt function as the default value for a function.

Here's my current code:

function custom_date($format = 'm-d-Y', $time = null)
{
    if($format == "d-m-Y") {
        // do something with $time
    }
    return date($format, $time);
}

I want to use time() as a default argument for $time instead of null, but it will not let me. I know I can pass time() as a 2nd argument to custom_date everywhere its called, but it's used at many places without 2nd argument and changing it would be a pain.

2 Answers 2

2

Just force $time to be equal to time() when there has been no value passed to the function.

function custom_date($format = 'm-d-Y', $time = null)
{
    $time = (null == $time) ? time() : $time;
    if($format == "d-m-Y") {
        // do something with $time
    }
    return date($format, $time);
 }
Sign up to request clarification or add additional context in comments.

2 Comments

I believe this is what OP really wanted. Give it a default of null, and check if it's null in the function.
Just FYI, > PHP 5.3 You can use $time = $time ?: time();
0

Try this.

function custom_date($format = 'm-d-Y', $func = 'time') {
if (function_exists($func)) {
    if ($format == "d-m-Y") {
        // do something with $time
    }
    return date($format, $func());
}elseif(is_numeric($func)){
    //timestamp logic
}}

2 Comments

this won't work either as in some cases, I am passing $time argument with timestamp value, and call_user_func(timestamp) would fail
@dhavald I just made a few changes to the above code. Hope that helps

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.