0

I have several functions in my code, who require more than 1 arguments.

I was using PHP 5.5, and whenever I input only the first argument, it worked fine, and simply ignored the second argument (I guess it saw it as "0").

But I've just upgraded to PHP 7.2 and this has become an issue.

So instead of fixing all of my code, which is spread on multiple files, is there a way to order PHP 7.2 to keep treating undefined arguments as "0", in order to avoid this Error, which is causing the page to crash?

EDIT:

sample function:

function calculate( $m,$status ) {

    return ''.$m.''.$status.'';

}

if $status doesn't exist, it should simply output $m

5
  • 1
    The proper fix (probably) involves changing the functions, not the callers. You'd have to add default values to arguments that aren't always provided. This may be less work than you think—how many functions are giving you this problem? Commented Apr 23, 2018 at 12:18
  • Folks, PHP 4.3.x through 7.0.x issued a warning but PHP 7.1+ is issuing a fatal exception. Commented Apr 23, 2018 at 12:20
  • I would see setting default values for these arguments as part of upgrading to PHP 7.2. If it's too much work, then don't upgrade that far. Stricter typing is one of the best reasons for upgrading to 7.x IMO followed by performance. Commented Apr 23, 2018 at 12:23
  • You can upgrade as far as PHP 7.0.29 without needing to fix your code. Commented Apr 23, 2018 at 12:24
  • Side note: You can change return ''.$m.''.$status.''; to return $m . $status;. The quotes aren't needed. Commented Apr 23, 2018 at 12:54

1 Answer 1

5

Easiest and cleanest way is to provide a default value for each parameter, making them optionals:

function myFunction ($requiredParam, $optionalInt = 0, $optionalStr = '') {
    //
}

then you can call myFunction(1); or myFunction(1,2); myFunction(1,2,'x'); without errors.

If you're curious about why this happens, it's beacuse

"Previously, a warning would be emitted for invoking user-defined functions with too few arguments. Now, this warning has been promoted to an Error exception. This change only applies to user-defined functions, not internal functions."

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. didn't know it was possible.
@rockyraw ;) glad to help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.