Tutorial :PHP Optional Function Arguments


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.


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'));  ?>  


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

From php.net:

Type hinting allowing NULL value


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



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


You can use other option:

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


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


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
Next Post »