Westy92
Westy92

Reputation: 21335

PHP Disable Deprecation Warnings for a Single Line

I currently have all errors enabled for my site:

error_reporting(E_ALL);

However, in PHP 8.1, some functions are now deprecated:

PHP Notice: Function date_sunset() is deprecated in index.php on line 14

Due to current requirements, I am unable to update the line to the non-deprecated alternative.

Is there a way to disable error reporting of deprecations just for this single line?

Upvotes: 3

Views: 11232

Answers (4)

FrancescoMM
FrancescoMM

Reputation: 2960

Just save your error preference state and then restore it later.

// Save current status
$savedErrorState = error_reporting();
// Set new preference
error_reporting($savedErrorState & ~E_DEPRECATED);

// Do something despicable and deprecated here

// restore previous status
error_reporting($savedErrorState);

Upvotes: 0

Max Pattern
Max Pattern

Reputation: 1698

Starting from PHP 8, you can add @ in front of your deprecated function.
With the @ you suppress the PHP error messages that would otherwise have been thrown at this point; or, more precisely, quoting the docs' first comment:

the error handler will still be called, but it will be called with an error level of 0

E.g.
@functionName(...)

Upvotes: 1

Westy92
Westy92

Reputation: 21335

As a workaround, you can wrap your deprecated line like this:

error_reporting(E_ALL & ~E_DEPRECATED);
// call_deprecated_function_here()
error_reporting(E_ALL);

Or if you wish to simply toggle the deprecated flag, use this:

error_reporting(error_reporting() ^ E_DEPRECATED); // toggle E_DEPRECATED (off)
// call_deprecated_function_here()
error_reporting(error_reporting() ^ E_DEPRECATED); // toggle E_DEPRECATED (back on)

Upvotes: 4

Paul T.
Paul T.

Reputation: 4917

The proposed workaround is only good until the function is removed, then it will only be fatal at some point whenever the function is removed, and a forced change will be imminent anyway.

Why not try to use what PHP's own API suggests?:

Relying on this function is highly discouraged. Use date_sun_info() instead.

See date_sun_info() ... there are less parameters though, depending upon what you may have used previously with date_sunset().

Upvotes: 0

Related Questions