PHP 8.6

Deprecated Features

PHP Core

Using "namespace" as a class constant name

Declaring a class constant named namespace is now deprecated. namespace is a semi-reserved keyword, and the name is being reserved for possible future syntax such as a ::namespace pseudo-constant analogous to ::class. Methods and static properties named namespace are not affected. Rename the constant, for example to NAMESPACE_NAME.

Returning from a finally block

Using the return statement inside a finally block is now deprecated, and emits a compile-time deprecation notice. Such a return silently discards an exception thrown by, or overwrites the value returned from, the associated try or catch block, so failures vanish without a trace. Move the return out of the finally block instead; the same result can always be expressed without it.

function getConfig(): array
{
    try {
        return loadConfig(); // throws if the file is missing
    } finally {
        return []; // Deprecated: the exception is gone, the caller just gets []
    }
}

Nullable return type for __debugInfo()

Declaring a return type of ?array for __debugInfo() is now deprecated. Returning null from this method was already deprecated in PHP 8.5, so the nullable return type no longer describes valid behaviour. Declare array instead.

Returning values from __construct() and __destruct()

Returning a value from __construct() or __destruct() is now deprecated, and emits a compile-time deprecation notice. These methods cannot declare a return type, and their return value can never be observed during normal use, which made returning a value confusing at best. Using return; without a value to skip the remaining logic is still allowed, as is calling these methods manually.

For the same reason, using yield to make __construct() or __destruct() a generator is now deprecated.

Naming a function readonly

Declaring a function named readonly is now deprecated. readonly is a reserved keyword; a lexer exception was added in PHP 8.1 solely to keep an existing WordPress function of that name working, and no other keyword in PHP receives such special treatment. Rename the function.

Using let, is, or _ as an identifier

Using let or is as the name of a class, interface, trait, enum, function, or constant (including via define()) is now deprecated, as is using either as the alias in a class_alias() call or in a use, use function, or use const declaration. The names are being reserved as keywords for potential future features: let for block scoping and is for pattern matching. Rename the affected symbols.

The deprecation of _ as a class name in PHP 8.4 is extended to constants: declaring a constant named _ with const or define(), and aliasing a class or constant to _ in a use declaration, are now deprecated. Functions named _, including the _() alias of gettext(), are not affected.

Third argument to define()

Passing the case_insensitive argument to define() is now deprecated. Case-insensitive constants were removed in PHP 8.0, since when the argument has been ignored. Explicitly passing false now emits a deprecation notice. Passing true continues to emit a warning, whose message now states that this will become an error in PHP 9.0. Omit the argument.

is_a() and is_subclass_of() with a string when allow_string is false

Calling is_a() or is_subclass_of() with a string as the first argument while allow_string is false is now deprecated. In that case the functions always return false, even when the class is already loaded, so such a call indicates a bug. To avoid triggering autoloading, check class_exists() with autoloading disabled first, and then call the function with allow_string set to true.

metaphone()

The metaphone() function is now deprecated. It implements the original 1990 Metaphone algorithm, which is limited to English pronunciation rules and has long been superseded by Double Metaphone and Metaphone 3. Phonetic algorithms are language-specific and frequently updated, so they are better served by a userland library; use one instead.

More than 16 filters in a php://filter URL

Using more than 16 filters in a php://filter URL without configuring the filter.max_filter_count stream context option now emits a deprecation notice. Long filter chains have no known legitimate use, but are the basis of a class of attacks that turn a local file inclusion or an arbitrary file read into remote code execution. When filter.max_filter_count is set explicitly, exceeding it is already an error: opening the stream fails with a warning.

Code that needs more filters should either add them with stream_filter_append() or stream_filter_prepend(), which are not limited, or raise the limit through the context option, for example globally with stream_context_set_default().

Passing objects to array_walk(), array_walk_recursive(), and http_build_query()

Passing an object as the array argument to array_walk() or array_walk_recursive() is now deprecated. A small number of functions silently interpret an object as the array of its visible properties. Modifying such properties through a by-reference callback violates readonly semantics and can corrupt enum cases, and array_walk_recursive() does not recurse into nested objects anyway. Call get_object_vars() on the object first and pass the resulting array.

Passing an object as the data argument to http_build_query() is now deprecated. Objects encountered as values within data now also emit a deprecation notice when they are interpreted as arrays. Treating objects as arrays has been a recurring source of confusion, in particular for Stringable objects, which users expect to be converted to a string instead. Convert objects to arrays with get_object_vars(), recursively if necessary, before calling the function.

is_double(), is_long(), is_integer(), and doubleval()

Following the deprecation of the non-canonical cast names in PHP 8.5, the function aliases that carry the same outdated type names are now deprecated. They behave identically to their canonical counterparts, which should be used instead:

strcoll() and SORT_LOCALE_STRING

The strcoll() function is now deprecated. It compares strings according to the LC_COLLATE setting of the current locale, which is global process state set via setlocale() that any library can change, it is not binary safe unlike every other string comparison function, and some locales do not implement correct collation rules. Use Collator::compare() from the intl extension instead, which is accurate and has up-to-date collation rules.

The SORT_LOCALE_STRING flag of the sort functions is now deprecated for the same reasons, as it sorts using strcoll(). Use one of the following methods of the Collator class instead:

Bzip2

Passing an object as the parameters of the bzip2.compress and bzip2.decompress stream filters is now deprecated, as only an associative array is documented and supported. Call get_object_vars() on the object first and pass the resulting array.

GMP

The shift (<<, >>) and exponentiation (**) operators on GMP objects now emit a deprecation notice when the right operand is a float whose conversion to int loses precision, consistent with the deprecation of implicit lossy float to int conversions elsewhere in the language.

MBString

The mbregex functions have been deprecated, because the underlying Oniguruma library is no longer maintained; its maintenance ended in April 2025. The functions will be removed in PHP 9.0. For most use cases the PCRE functions with the u modifier are a suitable replacement. The affected functions are:

The MB_ONIGURUMA_VERSION constant and the mbstring.regex_retry_limit and mbstring.regex_stack_limit INI directives are deprecated along with them.

Passing an object as the vars argument to mb_convert_variables() is now deprecated, as objects are silently interpreted as the array of their visible properties. Call get_object_vars() on the object first, or use mb_convert_encoding(), which converts arrays recursively and returns the result instead of modifying its argument in place.

MySQLi

The mysqli_get_charset() function and the mysqli::get_charset() method are now deprecated, without replacement. They expose internal implementation details of the character set that have been meaningless since the switch to mysqlnd; in particular the reported collation does not correspond to the collation defined by the server. To get the name of the current character set, use mysqli_character_set_name() or mysqli::character_set_name().

The mysqli_stmt_init() function and the mysqli::stmt_init() method are now deprecated. They create an empty statement object that still has to be prepared before use, and are a source of statement objects left in an inconsistent state. Use mysqli_prepare() or mysqli::prepare() instead, which prepare the statement in one step. For the same reason, calling the mysqli_stmt::__construct() constructor without the query parameter is now deprecated; pass the query to the constructor instead.

Reflection

Calling ReflectionProperty::setValue() or ReflectionProperty::setRawValue() with an object that is not an instance of the class on which the property was declared is now deprecated. Unlike the other ReflectionProperty methods, which throw for such objects, these methods silently set a property on the unrelated object, which is no better than a normal assignment and conceptually wrong.

Passing an object to ReflectionMethod::invoke() or ReflectionMethod::invokeArgs() when invoking a static method is now deprecated. Static methods have no $this, so the object was ignored entirely and never validated. Pass null instead.

Session

Passing an object that does not implement both the SessionIdInterface::create_sid() and SessionUpdateTimestampHandlerInterface::validateId() methods to session_set_save_handler() is now deprecated, regardless of which interfaces the object declares. These methods are required for a save handler to behave correctly under session.use_strict_mode, which is enabled by default as of PHP 8.6 and mitigates session fixation.

Accordingly, an E_WARNING is now emitted when a class implements SessionHandlerInterface without defining the SessionIdInterface::create_sid() or SessionUpdateTimestampHandlerInterface::validateId() methods. In PHP 9.0 these methods will be moved from SessionIdInterface and SessionUpdateTimestampHandlerInterface into SessionHandlerInterface, where they will be required. Implement both methods on custom save handlers now.

SPL

The spl_classes() function is now deprecated. No other extension exposes such a function, and the Reflection extension is always available. Use ReflectionExtension::getClassNames() instead.

The spl_object_hash() function is now deprecated. Since PHP 8.1 its return value has been nothing more than a reformatted spl_object_id(), and the name is misleading as the value is not derived from the contents of the object. The string form is also error-prone: two hashes can compare loosely equal because both are numeric strings. Use spl_object_id() instead.

The following ArrayIterator methods are now deprecated. They only exist because ArrayIterator historically shared its implementation with ArrayObject; most of them make little sense on an iterator and prevent optimizing its implementation. The corresponding ArrayObject methods are not deprecated.

The CSV methods of SplFileObject are now deprecated. Their historical design inconsistencies, further exposed by named arguments, have made them increasingly difficult to maintain, and CSV handling does not naturally belong in SplFileObject. Use fgetcsv() and fputcsv() on a stream instead.

Zlib

Passing an object as the parameters of the zlib.deflate and zlib.inflate stream filters is now deprecated, as only an associative array is documented and supported. Call get_object_vars() on the object first and pass the resulting array.

Passing an object as the options argument to deflate_init() or inflate_init() is now deprecated, as objects are silently interpreted as the array of their visible properties. Call get_object_vars() on the object first and pass the resulting array.

PHP 8.5

Deprecated Features

PHP Core

Changes to user output handler

Trying to produce output (e.g. with echo) within a user output handler is deprecated. The deprecation warning will bypass the handler producing the output to ensure it is visible; if there are nested output handlers the next one will still be used.

Non-canonical cast names

Non-canonical cast names (boolean), (integer), (double), and (binary) have been deprecated, use (bool), (int), (float), and (string) respectively.

Terminating case statements with a semicolon

Terminating case statements with a semicolon instead of a colon has been deprecated.

The backtick operator

The backtick operator as an alias for shell_exec() has been deprecated.

Returning null from __debugInfo()

Returning null from __debugInfo() has been deprecated. Return an empty array instead.

report_memleaks INI directive

The report_memleaks INI directive has been deprecated.

Constant redeclaration

Constant redeclaration has been deprecated. Note that this already generated a warning and will continue to do so.

Closure binding issues

The following closure binding issues, which already emit an E_WARNING, are now deprecated:

  • Binding an instance to a static closure.
  • Binding methods to objects that are not instances of the class (or subclass) that the method is defined.
  • Unbinding $this from a method.
  • Unbinding $this from a closure that uses `$this`.
  • Binding a closure to the scope of an internal class.
  • Rebinding the scope of a closure created from a function or method.

__sleep() and __wakeup() magic methods

The __sleep() and __wakeup() magic methods have been soft-deprecated. The __serialize() and __unserialize() magic methods should be used instead, or at the same time if compatibility with PHP 7 is required.

Using null as an array offset

Using null as an array offset or when calling array_key_exists() is now deprecated. Instead an empty string should be used.

Incrementing non-numeric strings

Incrementing non-numeric strings is now deprecated. Instead the str_increment() function should be used.

register_argc_argv INI directive

Deriving $_SERVER['argc'] and $_SERVER['argv'] from the query string for non-CLI SAPIs has been deprecated. Configure register_argc_argv=0 and switch to either $_GET or $_SERVER['QUERY_STRING'] to access the information, after verifying that the usage is safe.

cURL

The curl_close() function has been deprecated, as CurlHandle objects are freed automatically.

The curl_share_close() function has been deprecated, as CurlShareHandle objects are freed automatically.

Date

The DATE_RFC7231 and DateTimeInterface::RFC7231 constants have been deprecated. This is because the associated timezone is ignored and always uses GMT.

FileInfo

The finfo_close() function has been deprecated. As finfo objects are freed automatically.

The context parameter of the finfo_buffer() function has been deprecated as it is ignored.

GD

The imagedestroy() function has been deprecated, as GdImage objects are freed automatically.

Hash

The MHASH_* constants have been deprecated.

Intl

The intl.error_level INI setting has been deprecated. Errors should either be checked manually or exceptions should be enabled by using the intl.use_exceptions INI setting.

LDAP

Specific Oracle Instant Client calls and constants have been deprecated. List of affected calls:

List of affected constants:
  • GSLC_SSL_NO_UATH
  • GSLC_SSL_ONEWAY_UATH
  • GSLC_SSL_TWOWAY_UATH

MySQLi

The mysqli_execute() alias function has been deprecated. Use mysqli_stmt_execute() instead.

OpenSSL

The key_length parameter for openssl_pkey_derive() has been deprecated. This is because it is either ignored, or truncates the key, which can be a security vulnerability.

PDO

The "uri:" DSN scheme has been deprecated due to security concerns with DSNs coming from remote URIs.

Driver specific constants in the PDO class have been deprecated. List of affected constants and their replacement:

Driver specific methods in the PDO class have been deprecated. List of affected methods and their replacement:

PDO_PGSQL

Constants related to transaction states have been deprecated as this feature is unavailable with PDO:

Reflection

The setAccessible() methods of various Reflection objects have been deprecated, as those no longer have an effect.

Calling ReflectionClass::getConstant() for constants that do not exist has been deprecated.

Calling ReflectionProperty::getDefaultValue() for properties without default values has been deprecated.

SPL

Unregistering all autoloaders by passing the spl_autoload_call() function as a callback argument to spl_autoload_unregister() has been deprecated. Instead if this is needed, one should iterate over the return value of spl_autoload_functions() and call spl_autoload_unregister() on each value.

The SplObjectStorage::contains(), SplObjectStorage::attach(), and SplObjectStorage::detach() methods have been deprecated in favour of SplObjectStorage::offsetExists(), SplObjectStorage::offsetSet(), and SplObjectStorage::offsetUnset() respectively.

Using ArrayObject and ArrayIterator with objects has been deprecated.

Standard

The socket_set_timeout() alias function has been deprecated. Use stream_set_timeout() instead.

Passing null to readdir(), rewinddir(), and closedir() to use the last opened directory has been deprecated. Provide the last opened directory explicitly instead.

Passing integers outside the interval [0, 255] to chr() is now deprecated. This is because a byte can only hold a value within this interval.

Passing a string which is not a single byte to ord() is now deprecated, this is indicative of a bug.

The locally predefined variable $http_response_header is deprecated. Instead one should call the http_get_last_response_headers() function.

XML

The xml_parser_free() function has been deprecated, as XMLParser objects are freed automatically.

PHP 8.4

Deprecated Features

PHP Core

Implicitly nullable parameter

A parameter's type is implicitly widened to accept null if the default value for it is null.

The following code:

function foo(T1 $a = null) {}
should be converted to:
function foo(T1|null $a = null) {}
or
function foo(?T1 $a = null) {}

However, if such a parameter declaration is followed by a mandatory parameter:

function foo(T1 $a, T2 $b = null, T3 $c) {}
It must be converted to:
function foo(T1 $a, T2|null $b, T3 $c) {}
or
function foo(T1 $a, ?T2 $b, T3 $c) {}
as optional parameter before required ones are deprecated.

Raising zero to the power of negative number

Raising a number to the power of a negative number is equivalent to taking the reciprocal of the number raised to the positive opposite of the power. That is, 10-2 is the same as 1 / 102. Therefore raising 0 to the power of a negative number corresponds to dividing by 0, i.e. 0-2 is the same as 1 / 02, or 1 / 0. Thus, this behavior has been deprecated.

This affects the exponentiation operator ** and the pow() function.

If the IEEE 754 semantics are desired one should use the new fpow() function.

Using underscore _ as class name

Naming a class _ is now deprecated:

class _ {}

Note:

Classes whose names start with an underscore are not deprecated:

class _MyClass {}

Using trigger_error() with E_USER_ERROR

Calling trigger_error() with error_level being equal to E_USER_ERROR is now deprecated.

Such usages should be replaced by either throwing an exception, or calling exit(), whichever is more appropriate.

The E_STRICT constant

Because the E_STRICT error level was removed, this constant is now deprecated.

cURL

The CURLOPT_BINARYTRANSFER constant is now deprecated.

Date

The DatePeriod::__construct(string $isostr, int $options = 0) signature has been deprecated. Use DatePeriod::createFromISO8601String() instead.

The SUNFUNCS_RET_TIMESTAMP, SUNFUNCS_RET_STRING, and SUNFUNCS_RET_DOUBLE constants are now deprecated. This follows from the deprecation of the date_sunset() and date_sunrise() functions in PHP 8.1.0.

DBA

Passing null or false to dba_key_split() is now deprecated. It would always return false in those cases.

DOM

The DOM_PHP_ERR constant is now deprecated.

The following properties have been formally deprecated:

Hash

Passing invalid options to hash functions is now deprecated.

Intl

Calling intlcal_set() or IntlCalendar::set() with more than two arguments is deprecated. Use either IntlCalendar::setDate() or IntlCalendar::setDateTime() instead.

Calling intlgregcal_create_instance() or IntlGregorianCalendar::__construct() with more than two arguments is deprecated. Use either IntlGregorianCalendar::createFromDate() or IntlGregorianCalendar::createFromDateTime() instead.

LDAP

Calling ldap_connect() with more than two arguments is deprecated. Use ldap_connect_wallet() instead.

Calling ldap_exop() with more than four arguments is deprecated. Use ldap_exop_sync() instead.

MySQLi

The mysqli_ping() function and mysqli::ping() method are now deprecated as the reconnect feature was removed in PHP 8.2.0.

The mysqli_kill() function and mysqli::kill() method are now deprecated. If this functionality is needed a SQL KILL command can be used instead.

The mysqli_refresh() function and mysqli::refresh() method are now deprecated. If this functionality is needed a SQL FLUSH command can be used instead. All MYSQLI_REFRESH_* constants have been deprecated as well.

Passing the mode parameter to mysqli_store_result() explicitly has been deprecated. As the MYSQLI_STORE_RESULT_COPY_DATA constant was only used in conjunction with this function it has also been deprecated.

PDO_PGSQL

Using escaped question marks (??) inside dollar-quoted strings is deprecated. Because PDO_PGSQL now has its own SQL parser with dollar-quoted strings support, it is no longer necessary to escape question marks inside them.

PGSQL

The 2 arguments signature of pg_fetch_result(), pg_field_prtlen(), and pg_field_is_null() is now deprecated. Use the 3 arguments signature with row set to null instead.

Random

lcg_value() is now deprecated, as the function is broken in multiple ways. Use Random\Randomizer::getFloat() instead.

Reflection

Calling ReflectionMethod::__construct() with one argument is deprecated. Use ReflectionMethod::createFromMethodName() instead.

Session

Calling session_set_save_handler() with more than two arguments is deprecated. Use the two arguments signature instead.

Changing the value of the session.sid_length and session.sid_bits_per_character INI settings is deprecated. Update the session storage backend to accept 32 character hexadecimal session IDs and stop changing these two INI settings instead.

Changing the value of the session.use_only_cookies, session.use_trans_sid, session.trans_sid_tags, session.trans_sid_hosts, and session.referer_check INI settings is deprecated. The SID constant is also deprecated.

SOAP

Passing an int to SoapServer::addFunction() is now deprecated. If all PHP functions need to be provided flatten the array returned by get_defined_functions().

The SOAP_FUNCTIONS_ALL constant is now deprecated.

SPL

The SplFixedArray::__wakeup() method is now deprecated, as it implements SplFixedArray::__serialize() and SplFixedArray::__unserialize() which need to be overwritten instead.

Using the default value for the escape parameter for the SplFileObject::setCsvControl(), SplFileObject::fputcsv(), and SplFileObject::fgetcsv() is now deprecated. It must be passed explicitly either positionally or via named arguments. This does not apply to SplFileObject::fputcsv() and SplFileObject::fgetcsv() if SplFileObject::setCsvControl() was used to set a new default value.

Standard

Calling stream_context_set_option() with two arguments is deprecated. Use stream_context_set_options() instead.

Unserializing strings using the uppercase S tag with unserialize() is deprecated.

Using the default value for the escape parameter for the fputcsv(), fgetcsv(), and str_getcsv() is now deprecated. It must be passed explicitly either positionally or via named arguments.

XML

The xml_set_object() function has been deprecated.

Passing non-callable strings to the xml_set_* functions is now deprecated.

PHP 8.3

Deprecated Features

PHP Core

Saner Increment/Decrement operators

Using the increment operator (++) on empty, non-numeric, or non-alphanumeric strings is now deprecated. Moreover, incrementing non-numeric strings is soft deprecated. That means no E_DEPRECATED diagnostic is emitted, but this feature should not be used when producing new code. The new str_increment() function should be used instead.

Using the decrement operator (--) on empty or non-numeric strings is now deprecated.

get_class()/get_parent_class() call without arguments

Calling get_class() and get_parent_class() without arguments is now deprecated.

DBA

Calling dba_fetch() with dba as the 3rd argument is now deprecated.

FFI

Calling FFI::cast(), FFI::new(), and FFI::type() statically is now deprecated.

Intl

The U_MULTIPLE_DECIMAL_SEP*E*RATORS constant had been deprecated, using the U_MULTIPLE_DECIMAL_SEP*A*RATORS constant instead is recommended.

The NumberFormatter::TYPE_CURRENCY constant has been deprecated.

LDAP

Calling ldap_connect() with separate hostname and port is deprecated.

MBString

Passing a negative width to mb_strimwidth() is now deprecated.

Phar

Calling Phar::setStub() with a resource and a length is now deprecated. Such calls should be replaced by: $phar->setStub(stream_get_contents($resource));

Random

The MT_RAND_PHP Mt19937 variant is deprecated.

Reflection

Calling ReflectionProperty::setValue() with only one parameter is deprecated. To set static properties, pass null as the first parameter.

Standard

The assert_options() function is now deprecated.

The ASSERT_ACTIVE, ASSERT_BAIL, ASSERT_CALLBACK, ASSERT_EXCEPTION, and ASSERT_WARNING constants have been deprecated.

The assert.* INI settings have been deprecated. See the Changes to INI File Handling page for further details.

SQLite3

Using exceptions is now preferred, warnings will be removed in the future. Calling SQLite3::enableExceptions(false) will trigger a deprecation warning in this version.

Zip

The ZipArchive::FL_RECOMPRESS constant is deprecated and will be removed in a future version of libzip.

PHP 8.2

Deprecated Features

PHP Core

Usage of dynamic properties

The creation of dynamic properties is deprecated, unless the class opts in by using the #[\AllowDynamicProperties] attribute. stdClass allows dynamic properties. Usage of the __get()/__set() magic methods is not affected by this change. A dynamic properties deprecation warning can be addressed by:

  • Declaring the property (preferred).
  • Adding the #[\AllowDynamicProperties] attribute to the class (which also applies to all child classes).
  • Using a WeakMap if additional data needs to be associated with an object which one does not own.

Relative callables

Callables that are not accepted by the $callable() syntax (but are accepted by call_user_func()) are deprecated. In particular:

  • "self::method"
  • "parent::method"
  • "static::method"
  • ["self", "method"]
  • ["parent", "method"]
  • ["static", "method"]
  • ["Foo", "Bar::method"]
  • [new Foo, "Bar::method"]
This does not affect normal method callables such as "A::method" or ["A", "method"].

"${var}" and "${expr}" style interpolation

The "${var}" and "${expr}" style of string interpolation is deprecated. Use "$var"/"{$var}" and "{${expr}}", respectively.

MBString

Usage of the QPrint, Base64, Uuencode, and HTML-ENTITIES 'text encodings' is deprecated for all MBString functions. Unlike all the other text encodings supported by MBString, these do not encode a sequence of Unicode codepoints, but rather a sequence of raw bytes. It is not clear what the correct return values for most MBString functions should be when one of these non-encodings is specified. Moreover, PHP has separate, built-in implementations of all of them; for example, UUencoded data can be handled using convert_uuencode()/convert_uudecode().

SPL

The internal SplFileInfo::_bad_state_ex() method has been deprecated.

Standard

utf8_encode() and utf8_decode() have been deprecated.

PHP 8.1

Deprecated Features

PHP Core

Implementing Serializable without __serialize() and __unserialize()

Either only the new methods should be implemented, if no support for PHP prior to version 7.4 is provided, or both should be implemented.

Passing null to non-nullable parameters of built-in functions

Scalar types for built-in functions are nullable by default. This behaviour is deprecated to align with the behaviour of user-defined functions, where scalar types need to be marked as nullable explicitly.

(str_contains("foobar", null));
// Deprecated: Passing null to parameter #2 ($needle) of type string
//             is deprecated
?>

Implicit incompatible float to int conversions

The implicit conversion of float to int which leads to a loss in precision is now deprecated. This affects array keys, int type declarations in coercive mode, and operators working on ints.

= [];
$a[15.5]; // deprecated, as key value loses the 0.5 component
$a[15.0]; // ok, as 15.0 == 15
?>

Calling a static element on a trait

Calling a static method, or accessing a static property directly on a trait is deprecated. Static methods and properties should only be accessed on a class using the trait.

Returning a non-array from __sleep()

Returning a value which is not an array from __sleep() now generates a diagnostic.

Returning by reference from a void function

function &test(): void {}
?>
Such a function is contradictory, and already emits the following E_NOTICE when called: Only variable references should be returned by reference.

Autovivification from false

Autovivification is the process of creating a new array when appending to a value. Autovivification is prohibited from scalar values, false however was an exception. This is now deprecated.

= false;
$arr[] = 2;   // deprecated
?>

Note:

Autovivification from null and undefined values is still allowed:

// From undefined
$arr[] = 'some value';
$arr['doesNotExist'][] = 2;
// From null
$arr = null;
$arr[] = 2;
?>

ctype

Verifying non-string arguments

Passing a non-string argument is deprecated. In the future, the argument will be interpreted as a string instead of an ASCII codepoint. Depending on the intended behavior, the argument should either be cast to string or an explicit call to chr() should be made. All ctype_*() functions are affected.

Date

date_sunrise() and date_sunset() have been deprecated in favor of date_sun_info().

strptime() has been deprecated. Use date_parse_from_format() instead (for locale-independent parsing), or IntlDateFormatter::parse() (for locale-dependent parsing).

strftime() and gmstrftime() have been deprecated. Use date() instead (for locale-independent formatting), or IntlDateFormatter::format() (for locale-dependent formatting).

Filter

The FILTER_SANITIZE_STRING and FILTER_SANITIZE_STRIPPED filters are deprecated.

The filter.default INI directive is deprecated.

GD

The num_points of imagepolygon(), imageopenpolygon() and imagefilledpolygon() has been deprecated.

Hash

The mhash(), mhash_keygen_s2k(), mhash_count(), mhash_get_block_size(), and mhash_get_hash_name() functions have been deprecated. Use the hash_*() functions instead.

IMAP

The NIL constant has been deprecated. Use 0 instead.

Intl

Calling IntlCalendar::roll() with a bool argument is deprecated. Use 1 and -1 instead of true and false respectively.

Multibyte String

Calling mb_check_encoding() without any arguments is deprecated.

MySQLi

The mysqli_driver::$driver_version property has been deprecated. It was meaningless and outdated, use PHP_VERSION_ID instead.

Calling mysqli::get_client_info() or mysqli_get_client_info() with the mysqli argument has been deprecated. Call mysqli_get_client_info() without any arguments to obtain the version information of the client library.

The mysqli::init() method has been deprecated. Replace calls to parent::init() with parent::__construct().

OCI8

The oci8.old_oci_close_semantics INI directive is deprecated.

ODBC

odbc_result_all() has been deprecated.

PDO

The PDO::FETCH_SERIALIZE fetch mode has been deprecated.

PgSQL

Not passing the connection argument to all pgsql_*() functions has been deprecated.

SOAP

The ssl_method option of SoapClient::__construct() has been deprecated in favor of SSL stream context options.

Standard

Calling key(), current(), next(), prev(), reset(), or end() on objects is deprecated. Either convert the object to an array using get_mangled_object_vars() first, or use the methods provided by a class that implements Iterator, such as ArrayIterator, instead.

The auto_detect_line_endings INI directive is deprecated. If necessary, handle "\r" line breaks manually instead.

The FILE_BINARY and FILE_TEXT constants have been deprecated. They never had any effect.

PHP 8.0

Deprecated Features

PHP Core

  • If a parameter with a default value is followed by a required parameter, the default value has no effect. This is deprecated as of PHP 8.0.0 and can generally be resolved by dropping the default value, without a change in functionality:

    function test($a = [], $b) {} // Before
    function test($a, $b) {}      // After
    ?>

    One exception to this rule are parameters of the form Type $param = null, where the null default makes the type implicitly nullable. This usage remains allowed, but it is recommended to use an explicit nullable type instead:

    function test(A $a = null, $b) {} // Still allowed
    function test(?A $a, $b) {}       // Recommended
    ?>
  • Calling get_defined_functions() with exclude_disabled explicitly set to false is deprecated and no longer has an effect. get_defined_functions() will never include disabled functions.

Enchant

LibXML

libxml_disable_entity_loader() has been deprecated. As libxml 2.9.0 is now required, external entity loading is guaranteed to be disabled by default, and this function is no longer needed to protect against XXE attacks, unless the (still vulnerable) LIBXML_NOENT is used. In that case, it is recommended to refactor the code using libxml_set_external_entity_loader() to suppress loading of external entities.

PGSQL / PDO PGSQL

Standard Library

  • Sort comparison functions that return true or false will now throw a deprecation warning, and should be replaced with an implementation that returns an integer less than, equal to, or greater than zero.

    // Replace
    usort($array, fn($a, $b) => $a > $b);
    // With
    usort($array, fn($a, $b) => $a <=> $b);
    ?>

Zip

  • Using an empty file as ZipArchive is deprecated. Libzip 1.6.0 does not accept empty files as valid zip archives any longer. The existing workaround will be removed in the next version.

  • The procedural API of Zip is deprecated. Use ZipArchive instead. Iteration over all entries can be accomplished using ZipArchive::statIndex() and a for loop:

    // iterate using the procedural API
    assert(is_resource($zip));
    while ($entry = zip_read($zip)) {
        echo zip_entry_name($entry);
    }
    
    // iterate using the object-oriented API
    assert($zip instanceof ZipArchive);
    for ($i = 0; $entry = $zip->statIndex($i); $i++) {
        echo $entry['name'];
    }
    ?>

Reflection

PHP 7.4

Deprecated Features

PHP Core

Nested ternary operators without explicit parentheses

Nested ternary operations must explicitly use parentheses to dictate the order of the operations. Previously, when used without parentheses, the left-associativity would not result in the expected behaviour in most cases.

? 2 : 3 ? 4 : 5;   // deprecated
(1 ? 2 : 3) ? 4 : 5; // ok
1 ? 2 : (3 ? 4 : 5); // ok
?>

Parentheses are not required when nesting into the middle operand, as this is always unambiguous and not affected by associativity:

1 ? 2 ? 3 : 4 : 5 // ok

Array and string offset access using curly braces

The array and string offset access syntax using curly braces is deprecated. Use $var[$idx] instead of $var{$idx}.

(real) cast and is_real() function

The (real) cast is deprecated, use (float) instead.

The is_real() function is also deprecated, use is_float() instead.

Unbinding $this when $this is used

Unbinding $this of a non-static closure that uses $this is deprecated.

parent keyword without parent class

Using parent inside a class without a parent is deprecated, and will throw a compile-time error in the future. Currently an error will only be generated if/when the parent is accessed at run-time.

allow_url_include INI option

The allow_url_include ini directive is deprecated. Enabling it will generate a deprecation notice at startup.

Invalid characters in base conversion functions

Passing invalid characters to base_convert(), bindec(), octdec() and hexdec() will now generate a deprecation notice. The result will still be computed as if the invalid characters did not exist. Leading and trailing whitespace, as well as prefixes of type 0x (depending on base) continue to be allowed.

Using array_key_exists() on objects

Using array_key_exists() on objects is deprecated. Instead either isset() or property_exists() should be used.

Magic quotes functions

The get_magic_quotes_gpc() and get_magic_quotes_runtime() functions are deprecated. They always return false.

hebrevc() function

The hebrevc() function is deprecated. It can be replaced with nl2br(hebrev($str)) or, preferably, the use of Unicode RTL support.

convert_cyr_string() function

The convert_cyr_string() function is deprecated. It can be replaced by one of mb_convert_string(), iconv() or UConverter.

money_format() function

The money_format() function is deprecated. It can be replaced by the intl NumberFormatter functionality.

ezmlm_hash() function

The ezmlm_hash() function is deprecated.

restore_include_path() function

The restore_include_path() function is deprecated. It can be replaced by ini_restore('include_path').

Implode with historical parameter order

Passing parameters to implode() in reverse order is deprecated, use implode($glue, $parts) instead of implode($parts, $glue).

COM

Importing type libraries with case-insensitive constant registering has been deprecated.

Filter

FILTER_SANITIZE_MAGIC_QUOTES is deprecated, use FILTER_SANITIZE_ADD_SLASHES instead.

Multibyte String

Passing a non-string pattern to mb_ereg_replace() is deprecated. Currently, non-string patterns are interpreted as ASCII codepoints. In PHP 8, the pattern will be interpreted as a string instead.

Passing the encoding as 3rd parameter to mb_strrpos() is deprecated. Instead pass a 0 offset, and encoding as 4th parameter.

Lightweight Directory Access Protocol

ldap_control_paged_result_response() and ldap_control_paged_result() are deprecated. Pagination controls can be sent along with ldap_search() instead.

Reflection

Calls to ReflectionType::__toString() now generate a deprecation notice. This method has been deprecated in favor of ReflectionNamedType::getName() in the documentation since PHP 7.1, but did not throw a deprecation notice for technical reasons.

The export() methods on all Reflection classes are deprecated. Construct a Reflection object and convert it to string instead:

// ReflectionClass::export(Foo::class, false) is:
echo new ReflectionClass(Foo::class), "\n";

// $str = ReflectionClass::export(Foo::class, true) is:
$str = (string) new ReflectionClass(Foo::class);
?>

Socket

The AI_IDN_ALLOW_UNASSIGNED and AI_IDN_USE_STD3_ASCII_RULES flags for socket_addrinfo_lookup() are deprecated, due to an upstream deprecation in glibc.

PHP 7.3

Deprecated Features

PHP Core

Case-Insensitive Constants

The declaration of case-insensitive constants has been deprecated. Passing true as the third argument to define() will now generate a deprecation warning. The use of case-insensitive constants with a case that differs from the declaration is also deprecated.

Namespaced assert()

Declaring a function called assert() inside a namespace is deprecated. The assert() function is subject to special handling by the engine, which may lead to inconsistent behavior when defining a namespaced function with the same name.

Strip-Tags Streaming

The fgetss() function and the string.strip_tags stream filter have been deprecated. This also affects the SplFileObject::fgetss() method and gzgetss() function.

Data Filtering

The explicit usage of the constants FILTER_FLAG_SCHEME_REQUIRED and FILTER_FLAG_HOST_REQUIRED is now deprecated; both are implied for FILTER_VALIDATE_URL anyway.

Image Processing and GD

image2wbmp() has been deprecated.

Internationalization Functions

Usage of the Normalizer::NONE form throws a deprecation warning, if PHP is linked with ICU ≥ 56.

Multibyte String

The following undocumented mbereg_*() aliases have been deprecated. Use the corresponding mb_ereg_*() variants instead.

  • mbregex_encoding()

  • mbereg()

  • mberegi()

  • mbereg_replace()

  • mberegi_replace()

  • mbsplit()

  • mbereg_match()

  • mbereg_search()

  • mbereg_search_pos()

  • mbereg_search_regs()

  • mbereg_search_init()

  • mbereg_search_getregs()

  • mbereg_search_getpos()

  • mbereg_search_setpos()

ODBC and DB2 Functions (PDO_ODBC)

The pdo_odbc.db2_instance_name ini setting has been formally deprecated. It is deprecated in the documentation as of PHP 5.1.1.

PHP 7.2

Deprecated features in PHP 7.2.x

Unquoted strings

Unquoted strings that are non-existent global constants are taken to be strings of themselves. This behaviour used to emit an E_NOTICE, but will now emit an E_WARNING. In the next major version of PHP, an Error exception will be thrown instead.

(NONEXISTENT);

/* Output:
Warning: Use of undefined constant NONEXISTENT - assumed 'NONEXISTENT' (this will throw an Error in a future version of PHP) in %s on line %d
string(11) "NONEXISTENT"
*/

png2wbmp() and jpeg2wbmp()

The png2wbmp() and jpeg2wbmp() functions from the GD extension have now been deprecated and will be removed in the next major version of PHP.

INTL_IDNA_VARIANT_2003 variant

The Intl extension has deprecated the INTL_IDNA_VARIANT_2003 variant, which is currently being used as the default for idn_to_ascii() and idn_to_utf8(). PHP 7.4 will see these defaults changed to INTL_IDNA_VARIANT_UTS46, and the next major version of PHP will remove INTL_IDNA_VARIANT_2003 altogether.

__autoload() method

The __autoload() method has been deprecated because it is inferior to spl_autoload_register() (due to it not being able to chain autoloaders), and there is no interoperability between the two autoloading styles.

track_errors ini setting and $php_errormsg variable

When the track_errors ini setting is enabled, a $php_errormsg variable is created in the local scope when a non-fatal error occurs. Given that the preferred way of retrieving such error information is by using error_get_last(), this feature has been deprecated.

create_function() function

Given the security issues of this function (being a thin wrapper around eval()), this dated function has now been deprecated. The preferred alternative is to use anonymous functions.

mbstring.func_overload ini setting

Given the interoperability problems of string-based functions being used in environments with this setting enabled, it has now been deprecated.

(unset) cast

Casting any expression to this type will always result in null, and so this superfluous casting type has now been deprecated.

parse_str() without a second argument

Without the second argument to parse_str(), the query string parameters would populate the local symbol table. Given the security implications of this, using parse_str() without a second argument has now been deprecated. The function should always be used with two arguments, as the second argument causes the query string to be parsed into an array.

gmp_random() function

This function generates a random number based upon a range that is calculated by an unexposed, platform-specific limb size. Because of this, the function has now been deprecated. The preferred way of generating a random number using the GMP extension is by gmp_random_bits() and gmp_random_range().

each() function

This function is far slower at iteration than a normal foreach, and causes implementation issues for some language changes. It has therefore been deprecated.

assert() with a string argument

Using assert() with a string argument required the string to be eval()'ed. Given the potential for remote code execution, using assert() with a string argument has now been deprecated in favour of using boolean expressions.

$errcontext argument of error handlers

The $errcontext argument contains all local variables of the error site. Given its rare usage, and the problems it causes with internal optimisations, it has now been deprecated. Instead, a debugger should be used to retrieve information on local variables at the error site.

read_exif_data() function

The read_exif_data() alias has been deprecated. The exif_read_data() function should be used instead.

PHP 7.1

Deprecated features in PHP 7.1.x

ext/mcrypt

The mcrypt extension has been abandonware for nearly a decade now, and was also fairly complex to use. It has therefore been deprecated in favour of OpenSSL, where it will be removed from the core and into PECL in PHP 7.2.

Eval option for mb_ereg_replace() and mb_eregi_replace()

The e pattern modifier has been deprecated for the mb_ereg_replace() and mb_eregi_replace() functions.

PHP 7.0

Deprecated features in PHP 7.0.x

PHP 4 style constructors

PHP 4 style constructors (methods that have the same name as the class they are defined in) are deprecated, and will be removed in the future. PHP 7 will emit E_DEPRECATED if a PHP 4 constructor is the only constructor defined within a class. Classes that implement a __construct() method are unaffected.

class foo {
    function foo() {
        echo 'I am the constructor';
    }
}
?>

The above example will output:

Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; foo has a deprecated constructor in example.php on line 3

Static calls to non-static methods

Static calls to methods that are not declared static are deprecated, and may be removed in the future.

class foo {
    function bar() {
        echo 'I am not static!';
    }
}

foo::bar();
?>

The above example will output:

Deprecated: Non-static method foo::bar() should not be called statically in - on line 8
I am not static!

password_hash() salt option

The salt option for the password_hash() function has been deprecated to prevent developers from generating their own (usually insecure) salts. The function itself generates a cryptographically secure salt when no salt is provided by the developer - therefore custom salt generation should not be needed.

capture_session_meta SSL context option

The capture_session_meta SSL context option has been deprecated. SSL metadata is now available through the stream_get_meta_data() function.

LDAP deprecations

The following function has been deprecated:

PHP 5.6

Deprecated features in PHP 5.6.x

Calls from incompatible context

Methods called from an incompatible context are now deprecated, and will generate E_DEPRECATED errors when invoked instead of E_STRICT. Support for these calls will be removed in a future version of PHP.

An example of such a call is:

class A {
    function f() { echo get_class($this); }
}

class B {
    function f() { A::f(); }
}

(new B)->f();
?>

The above example will output:

Deprecated: Non-static method A::f() should not be called statically, assuming $this from incompatible context in - on line 7
B

$HTTP_RAW_POST_DATA and always_populate_raw_post_data

always_populate_raw_post_data will now generate an E_DEPRECATED error when $HTTP_RAW_POST_DATA is populated. New code should use php://input instead of $HTTP_RAW_POST_DATA, which will be removed in a future release. You can opt in for the new behaviour (in which $HTTP_RAW_POST_DATA is never defined hence no E_DEPRECATED error will be generated) by setting always_populate_raw_post_data to -1.

iconv and mbstring encoding settings

The iconv and mbstring configuration options related to encoding have been deprecated in favour of default_charset. The deprecated options are:

PHP 5.5

Deprecated features in PHP 5.5.x

ext/mysql deprecation

The original MySQL extension is now deprecated, and will generate E_DEPRECATED errors when connecting to a database. Instead, use the MySQLi or PDO_MySQL extensions.

preg_replace() /e modifier

The preg_replace() /e modifier is now deprecated. Instead, use the preg_replace_callback() function.

intl deprecations

IntlDateFormatter::setTimeZoneID() and datefmt_set_timezone_id() are now deprecated. Instead, use the IntlDateFormatter::setTimeZone() method and datefmt_set_timezone() function, respectively.

mcrypt deprecations

The following functions have been deprecated:

PHP 5.3

Deprecated features in PHP 5.3.x

PHP 5.3.0 introduces two new error levels: E_DEPRECATED and E_USER_DEPRECATED. The E_DEPRECATED error level is used to indicate that a function or feature has been deprecated. The E_USER_DEPRECATED level is intended for indicating deprecated features in user code, similarly to the E_USER_ERROR and E_USER_WARNING levels.

The following is a list of deprecated INI directives. Use of any of these INI directives will cause an E_DEPRECATED error to be thrown at startup.

Deprecated functions:

Deprecated features:

  • Assigning the return value of new by reference is now deprecated.
  • Call-time pass-by-reference is now deprecated.