Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass current year as default argument in php function [duplicate]

Tags:

date

php

datetime

I want to pass the current Year as one of the default value of a function

I AM using

date("Y")

for current year

So it work fine when i write function in this way:

function MYfUNCTION($month,$year = 2013)
{
}

But I want to pass current year instead of 2013 but it gives me an error when i write like this

function MYfUNCTION($month,$year = date("Y"))
{
}

Please help me

like image 468
Akarsh Satija Avatar asked Dec 11 '13 13:12

Akarsh Satija


People also ask

Can we add two default values in function in PHP?

default parameters only work as the last arguments to the function. If you want to declare the default values in the function definition, there is no way to omit one parameter and override one following it.

How will you passing an argument to a function in PHP?

PHP Function ArgumentsArguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

What is default argument in PHP precedence?

The default arguments must be constant expressions. They cannot be variables or function calls. PHP allows you to use a scalar value, an array, and null as the default arguments.

What does ?: Mean in PHP?

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.


3 Answers

You can't use a function for a default argument value :

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

(extract from PHP doc)

You should set the default value into the function :

function myFunction($month, $year = null) 
{    
  if(!(bool)$year) {
    $year = date('Y');
  }
  echo $year.', '.$month;
}

myFunction('June', '2006'); // 2006, June
myFunction(3, 2010);        // 2010, 3
myFunction('July');         // 2013, July
like image 141
zessx Avatar answered Nov 14 '22 21:11

zessx


You can try this,

function MYfUNCTION($month,$year ="")
{
   if(empty($year)){
      $year = date($year); //Output: current year
   } 

   echo "Year: " . $year ." Month: " . $month;
}
like image 28
Krish R Avatar answered Nov 14 '22 20:11

Krish R


No direct method to pass arguments directly in the pre-defined format, you have to pass function putting the year you want to and you can make 1 more function in which you can change the year. like in php get curr year func. !! hope this can help.

like image 33
vaibhavdos Avatar answered Nov 14 '22 22:11

vaibhavdos