简体   繁体   中英

PHP: Function with 3 arguments > Use it with less arguments

I just created a function to add years|months|days to date. But I have a small issue, sometimes I want to add just years, but since the function has 3 arguments (years,months, days), I get a warning:

Warning: Missing argument 2 for addDate(), called in C:\\xampp\\htdocs\\date.php on line 10 and defined in C:\\xampp\\htdocs\\date.php on line 2

Warning: Missing argument 3 for addDate(), called in C:\\xampp\\htdocs\\date.php on line 10 and defined in C:\\xampp\\htdocs\\date.php on line 2

<?php 
function addDate($years, $months, $days)
{
    $currentDate = date('Y-m-d');

    $newDate = date('Y-m-d', strtotime($currentDate. '+'. $years. ' years +'. $months. ' months +'. $days. ' days'));
    echo $newDate;
}

addDate(2);
?>

I've tried to use addDate(2, null, null); but It doesn't work.

You can define a default value for the parameter, like,

function addDate($years = 0, $months = 0, $days = 0)
{

Might be better to check whether each is >0 before building the string:

$newDateString = '';
if ( $years > 0 ) $newDateString .= " +$years years";
if ( $months > 0 ) $newDateString .= " +$months months";
if ( $days > 0 ) $newDateString .= " +$days days";
$newDate = date('Y-m-d', strtotime( date('Y-m-d') . $newDateString ) );

Lastly, you will (probably) want to be passing the value back using return rather than echo() ing - allows for more versatility later down the line:

    return $newDate;

And calling it like so:

echo addDate( 2 );

Function altogether:

function addDate($years = 0, $months = 0, $days = 0)
{
    $newDateString = '';
    if ( $years > 0 ) $newDateString .= " +$years years";
    if ( $months > 0 ) $newDateString .= " +$months months";
    if ( $days > 0 ) $newDateString .= " +$days days";
    return date('Y-m-d', strtotime($currentDate . $newDateString ) );
}

You can declare default values for parameter:

function addDate($years, $months = 0, $days = 0)

This way you don't need to specify those or call your function like 'addDate(2,0,0)'

See http://php.net/manual/functions.arguments.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM