Tutorial :PHP Optional Function Arguments



Question:

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.


Solution:1

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


Solution:2

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


Solution:3

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());  


Solution:4

You can use other option:

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


Solution:5

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


Solution:6

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


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »