briannesbitt / Carbon

A simple PHP API extension for DateTime.
https://carbon.nesbot.com/
MIT License
16.58k stars 1.28k forks source link

Singular methods without parameters also work with parameters. It should not be as per the documentation. #3025

Closed MrPunyapal closed 6 months ago

MrPunyapal commented 6 months ago

Carbon: "^2.71.0 || ^3.0.0",

My code:

dd(
        Carbon::now()->addMonth(2)->format('Y-m-d'),
        Carbon::now()->addMonths(2)->format('Y-m-d')
);

Output: image

as per docs, it should not add more than one month in add month. image

kylekatarnls commented 6 months ago

Hello, they are both handled by the magic __call and the unit is normalized so to allow both with or without s.

In practice they are indeed just alias one for each other. And because the default value is 1, calling it with no parameters will add 1 unit.

But we recommend to use it semantically (to make the code unambiguous and easier to understand) following the rules below:

(the plural method is meant to pass either a value different than 1 or a dynamic value (variable, function call result, etc.)

I considered already to make the parameter mandatory for plural method and throw an exception when passing argument to the singular method, but this is a breaking change and it has a lot of indirect consequences that can make it hard for all the users to update (most people have carbon as a sub-dependency so they don't control easily which version they have, that's why we need to proceed breaking changes with parsimony).

As a first step (when stepping from 2.x to 3.x) the type has moved from PHPDoc to concrete type hint (previously it was practically possible to pass null or false.

For the documentation, here it aims to tell how to use in a way that is relevant and is guaranteed to work on the long run, calling ->addMonth(2) or ->addMonths() will likely trigger an deprecation notice, then an error in a later version, so I advise to consider following the documentation even if at the moment it's not enforced at runtime.