0

I'm a little stuck trying to create a function that takes a single, optional argument. Instead of this being a string I'd like it to be the result of a function (or even better, a DateTime object). Essentially - I want the user to either pass in a DateTime object, or for the function to resort to todays date if no arguments are supplied. Is this possible with PHP? By trying to create the new object in the function header as such

function myDateFunction($date = new DateTime()){
//My function goes here.
}

causes PHP to fall over.

Many thanks.

6 Answers 6

5

Yes. It is possible if you move $date instantiation to function body:

<?php
header('Content-Type: text/plain');

function myDateFunction(DateTime $date = null){
    if($date === null){
        $date = new DateTime();
    }

    return $date->format('d.m.Y H:i:s');
}

echo
    myDateFunction(),
    PHP_EOL,
    myDateFunction(DateTime::createFromFormat('d.m.Y', '11.11.2011'));
?>

Result:

15.09.2013 17:25:02
11.11.2011 17:25:02

From php.net:

Type hinting allowing NULL value

Sign up to request clarification or add additional context in comments.

1 Comment

"Yes. it is possible:" --- it's not. Don't confuse newbies
5

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

http://php.net/manual/en/functions.arguments.php#example-154

Comments

2

You can do it this way:

function myDateFunction($date = null){
    if(is_null($date) || !($date instanceof DateTime)) {
        $date = new DateTime();
    }

    return $date;
}

var_dump(myDateFunction());

4 Comments

Thank you sir for copying the solution that I've suggested with a minor modification(Who ever edited this).
Haha, @OlegTikhonov, I didn't.
Last time I've checked, PHP evaluates if(!($date instanceof DateTime)) the same as if($date !instanceof DateTime) but nevermind :)
@OlegTikhonov: checked times: me ( answered 59 mins ago ), you ( answered 58 mins ago ) ;)
1

You can use other option:

function myDateFunction($date = null){
 if(is_null($date)) $date = new DateTime();

}

Comments

1
function myDateFunc($date = null){
   if(!isset($date) || $date !instanceof DateTime){
     $date = new DateTime()
   }
   /* YOur code here*/
}

Comments

0

for optional argument in your function, you can write code like

function myDateFunction($date = ''){
         //My function goes here.
         if($date==''){ $date = new DateTime()}
    }

hope it helps

1 Comment

It's conventionally to use null instead of empty string to express the lack of data passed.

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.