Alterações incompatíveis com versões anteriores

PHP Core

Comparação entre String e Número

Comparações não estritas entre números e strings não numéricas, agora funcionam convertendo o número em string e comparando as strings. As comparações entre números e strings numéricas continuam a funcionando como antes. Notavelmente, isso significa que a comparação: 0 == "nao-numero" agora é considerada falsa.

Comparação Antes Depois
0 == "0" true true
0 == "0.0" true true
0 == "foo" true false
0 == "" true false
42 == " 42" true true
42 == "42foo" true false

Outras mudanças incompatíveis

  • match é agora uma palavra reservada.

  • As falhas de asserção agora são lançadas por padrão. Se o comportamento antigo é desejado, assert.exception=0 pode ser definido nas configurações INI.

  • Métodos com o mesmo nome de classe não são mais interpretados como construtor. O método __construct() deve ser utilizado em seu lugar.

  • A capacidade de chamar métodos não estáticos estaticamente foi removida. Por isso is_callable() irá falhar ao verificar um método não estático com um nome de classe (deve se realizar uma verificação com uma instância de objeto).

  • Foram removidos os casts (real) e (unset).

  • A diretiva track_errors no php.ini foi removida. Isto signifca que o php_errormsg não está mais disponível. A função error_get_last() deve ser utilizada em seu lugar.

  • A capacidade de definir constantes que não diferenciam maiúsculas de minúsculas foi removida. O terceiro argumento para a função define() não pode ser mais true.

  • A capacidade de especificar um auto carregamento utilizando a função __autoload() foi removida. A função spl_autoload_register() deve ser utilizada em seu lugar.

  • O argumento errcontext para manipulador de erros personalizados foi removido.

  • create_function() foi removido. Ao invés disso, funções anônimas devem ser utilizadas.

  • A função each() foi removida. foreach ou ArrayIterator devem ser utilizados em seu lugar.

  • Foi removida a capacidade de desvincular this de closures que foram criados a partir de um método, usando Closure::fromCallable() ou ReflectionMethod::getClosure().

  • A habilidade de desvincular this de closures que contêm usos de this também foi removida.

  • A habilidade de utilizar array_key_exists() com objetos foi removida. isset() or property_exists() may be used instead.

  • O comportamento da função array_key_exists() com relação ao tipo do parâmetro key agora é consistente com a função isset() e acesso normal à array. Todos os tipos de chave agora usam as coerções usuais e as chaves de array/objeto lançam um TypeError.

  • Qualquer array com número n em sua primeira posição utilizará n+1 em sua próxima chave implícita mesmo se n for negativo.

  • O nível de error_reporting padrão é E_ALL. Anteriormente excluía E_NOTICE e E_DEPRECATED.

  • display_startup_errors é habilitado agora por padrão.

  • Usar parent dentro de uma classe sem pai agora produzirá um erro fatal em tempo de execução.

  • O operador @ não irá mais silenciar erros fatais (E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR, E_PARSE). Manipuladores de erros que esperam que error_reporting seja 0 quando @ é usado, devem ser ajustados para usar uma verificação de máscara:

    <?php
    // Replace
    function my_error_handler($err_no$err_msg$filename$linenum) {
        if (
    error_reporting() == 0) {
            return 
    false// Silenced
        
    }
        
    // ...
    }

    // With
    function my_error_handler($err_no$err_msg$filename$linenum) {
        if (!(
    error_reporting() & $err_no)) {
            return 
    false// Silenced
        
    }
        
    // ...
    }
    ?>

    Adicionalmente, cuidados devem ser tomados para que mensagens de erro não sejam mostradas no ambiente de produção, o que podem resultar em vazamento de informações. Certifique-se de que a diretiva display_errors=Off seja usada em conjunto com o log de erros.

  • #[ não é mais interpretado como o início de um comentário, já que esta sintaxe é utilizada agora para atributos.

  • Inheritance errors due to incompatible method signatures (LSP violations) will now always generate a fatal error. Previously a warning was generated in some cases.

  • A precedência dos operadores de concatenação foi modificada em relação ao bitshifts tanto na adição como na subtração

    <?php
    echo "Sum: " $a $b;
    // was previously interpreted as:
    echo ("Sum: " $a) + $b;
    // is now interpreted as:
    echo "Sum:" . ($a $b);
    ?>

  • Argumentos com um valor padrão que avaliam para null em tempo de execução, não irão mais marcar o tipo do parâmetro como implícito. Um tipo explícito nulo, ou explicitamente null como argumento padrão deve ser usado em seu lugar.

    <?php
    // Replace
    function test(int $arg CONST_RESOLVING_TO_NULL) {}
    // With
    function test(?int $arg CONST_RESOLVING_TO_NULL) {}
    // Or
    function test(int $arg null) {}
    ?>

  • Uma série de avisos foram convertidos para exceções do tipo Error:

    • Attempting to write to a property of a non-object. Previously this implicitly created an stdClass object for null, false and empty strings.
    • Attempting to append an element to an array for which the PHP_INT_MAX key is already used.
    • Attempting to use an invalid type (array or object) as an array key or string offset.
    • Attempting to write to an array index of a scalar value.
    • Attempting to unpack a non-array/Traversable.
    • Attempting to access unqualified constants which are undefined. Previously, unqualified constant accesses resulted in a warning and were interpreted as strings.

    Uma série de notificações foram convertidas em avisos:

    • Tentativa de leitura em uma variável não definida.
    • Tentativa de leitura em uma propriedade não definida.
    • Tentativa de leitura em uma chave de array não definido.
    • Tentativa de leitura em uma propriedade de um não objeto.
    • Tentativa de acesso em um índice de array em um não array.
    • Tentativa de conversão de um array para uma string.
    • Tentativa de usar um resource como uma chave de array.
    • Tentativa de usar null, um booleano ou um número de ponto flutuante(float) como uma posinção em uma string.
    • Tentativa de leitura em uma posição fora dos limites de uma string.
    • Tentativa de atribuir uma string vazia a uma posição de uma string.

  • Tentativa de atribuir multiplos bytes em uma posição de uma string agora emite um aviso.

  • Caracteres inesperados no arquivo fonte (como bytes NUL fora de strings) agora irá resultar em uma exceção ParseError ou invés de um aviso do compilador.

  • As exceções não capturadas agora passam por "desligamento limpo", o que significa que os destrutores são chamados após uma exceção não detectada.

  • O erro fatal de tempo de compilação "Somente variáveis podem ser passadas por referência" foi adiado até o runtime, e convertido em uma exceção de Error "argumento não pode ser passado por referência".

  • Alguns alertas do tipo "Somente variáveis podem ser passadas por referência" foram convertidas para exceções do tipo "Argumento deve ser passado por referência"

  • O nome gerado para classes anônimas foi modificado. Agora, inclui o nome do primeira classe ou interface:

    <?php
    new class extends ParentClass {};
    // -> ParentClass@anonymous
    new class implements FirstInterfaceSecondInterface {};
    // -> FirstInterface@anonymous
    new class {};
    // -> class@anonymous
    ?>

    O nome mostrado acima ainda é seguido por um byte NUL e um sufixo exclusivo.

  • As referências de método de traço não absoluto em adaptações de alias de traço agora precisam ser inequívocas:

    <?php
    class {
        use 
    T1T2 {
            
    func as otherFunc;
        }
        function 
    func() {}
    }
    ?>

    Se T1::func() e T2::func() existem, este código anteriormente foi aceito de forma silenciosa e func assumia referência a T1::func. Agora vai gerar um erro fatal, e T1::func ou T2::func precisam ser escritos explicitamente.

  • A assinatura de métodos abstratos definido nas características agora é verificada no método de implementação da classe:

    <?php
    trait MyTrait {
        abstract private function 
    neededByTrait(): string;
    }

    class 
    MyClass {
        use 
    MyTrait;

        
    // Error, because of return type mismatch.
        
    private function neededByTrait(): int { return 42; }
    }
    ?>

  • Funções desabilitadas agora são tratadas da mesma forma que funções não existentes. Ao chamar uma função desabilitada será informado que ela é desconhecida, e redefinir uma função desabilitada é agora possível.

  • Os stream wrappers data:// não podem mais ser writable, indo de encontro ao comportamento documentado.

  • Os operadores aritméticos e bit a bit +, -, *, /, **, %, <<, >>, &, |, ^, ~, ++, -- irá agora apresentar um TypeError quando um dos operandos estiver em um array, resource ou em um object não sobrecarregado. A unica exceção a isto é a operação de mesclagem de array com +, que permanece suportada.

  • A conversão de float para string agora sempre terá o mesmo comportamento, independentemente da localidade.

    <?php
    setlocale
    (LC_ALL"de_DE");
    $f 3.14;
    echo 
    $f"\n";
    // Previously: 3,14
    // Now:        3.14
    ?>

    Veja as funções printf(), number_format() and NumberFormatter() para customizar a formatação de números.

  • Support for deprecated curly braces for offset access has been removed.

    <?php
    // Instead of:
    $array{0};
    $array{"key"};
    // Write:
    $array[0];
    $array["key"];
    ?>

  • Aplicando o modificador final ou método privado agora irá produzir um aviso a menos que o método seja o construtor.

  • Se um objeto construtor chama a função exit(), o objeto destrutor não será chamado. Isto vai de encontro ao comportamento que o contrutor executa.

  • Nomes de Namespace não podem mais conter espaços em branco: Enquanto Foo\Bar será reconhecido como um nome de Namespace, Foo \ Bar não será. Por outro lado, as palavras-chave agora serão permitidos como segmentos de um namespace, o que permite a mudança na interpretação do código: new\x agora é o mesmo que constant('new\x'), e não new \x().

  • Os ternários aninhados agora exigem parênteses explícitos.

  • debug_backtrace() e Exception::getTrace() agora não mais apresentam referencias aos argumentos. Não será possivel mudar os argumentos de uma função através de um backtrace.

  • O uso de strings numéricas foi modificado para ser mais intuitivo e menos sujeito a erros. Seguindo os espaços em branco, é permitido agora strings numéricas para tratamento de consistência contendo espaços em branco. Isso afeta principalmente:

    • A funcção is_numeric()
    • Comparação string a string
    • Declaração de tipos
    • Operações de incremento e decremento

    O conceito de um "leading-numeric string" foi praticamente abandonado; os casos onde permanecem são para facilitar a migração. Strings que emitem um E_NOTICE "Um valor numerico não bem formado foi encontrado" agora emitirá um E_WARNING "Um valor valor não numérico encontrado " e todas as strings que emitiram um E_WARNING "Um valor não numerico encontrado" agora produzirá um erro TypeError. Isso afeta principalmente:

    • Operações aritméticas
    • Operações bit a bit

    Esta mudança do E_WARNING para TypeError também afeta o E_WARNING "Illegal string offset 'string'" para o posicionamente ilegal de strings. O comportamento de conversões explícitas de strings para int/float não foi alterado.

  • Métodos mágicos agora podem ter argumentos e retornar tipos verificados se eles foram declarados. As assinaturas devem corresponder à seguinte lista:

    • __call(string $name, array $arguments): mixed
    • __callStatic(string $name, array $arguments): mixed
    • __clone(): void
    • __debugInfo(): ?array
    • __get(string $name): mixed
    • __invoke(mixed $arguments): mixed
    • __isset(string $name): bool
    • __serialize(): array
    • __set(string $name, mixed $value): void
    • __set_state(array $properties): object
    • __sleep(): array
    • __unserialize(array $data): void
    • __unset(string $name): void
    • __wakeup(): void

  • As chaves do array call_user_func_array() agora podem ser interpretadas como nomes de parãmetros, ao invés de serem silenciosamente ignorados.

  • A declaração da função chamada assert() dentro de um namespace não é mais permitida e gera um E_COMPILE_ERROR. A funçãi assert() recebe um tratamento especial pelo motor do PHP, o que pode levar a comportamentos inconsistentes quando definido como uma função de namespace com o mesmo nome.

Migração de Resource para Objeto

Diversos resources foram migrados para objects. Return value checks using is_resource() should be replaced with checks for false.

COM and .Net (Windows)

The ability to import case-insensitive constants from type libraries has been removed. The second argument to com_load_typelib() may no longer be false; com.autoregister_casesensitive may no longer be disabled; case-insensitive markers in com.typelib_file are ignored.

CURL

CURLOPT_POSTFIELDS no longer accepts objects as arrays. To interpret an object as an array, perform an explicit (array) cast. The same applies to other options accepting arrays as well.

Date and Time

mktime() and gmmktime() now require at least one argument. time() can be used to get the current timestamp.

DOM

Unimplemented classes from the DOM extension that had no behavior and contained test data have been removed. These classes have also been removed in the latest version of the DOM standard:

  • DOMNameList
  • DomImplementationList
  • DOMConfiguration
  • DomError
  • DomErrorHandler
  • DOMImplementationSource
  • DOMLocator
  • DOMUserDataHandler
  • DOMTypeInfo

Enchant

Exif

read_exif_data() has been removed; exif_read_data() should be used instead.

Filter

  • The FILTER_FLAG_SCHEME_REQUIRED and FILTER_FLAG_HOST_REQUIRED flags for the FILTER_VALIDATE_URL filter have been removed. The scheme and host are (and have been) always required.

  • The INPUT_REQUEST and INPUT_SESSION source for filter_input() etc. have been removed. These were never implemented and their use always generated a warning.

GD

  • The deprecated functions image2wbmp() has been removed.

  • The deprecated functions png2wbmp() and jpeg2wbmp() have been removed.

  • The default mode parameter of imagecropauto() no longer accepts -1. IMG_CROP_DEFAULT should be used instead.

  • On Windows, php_gd2.dll has been renamed to php_gd.dll.

GMP

gmp_random() has been removed. One of gmp_random_range() or gmp_random_bits() should be used instead.

Iconv

iconv implementations which do not properly set errno in case of errors are no longer supported.

IMAP

Internationalization Functions

  • The deprecated constant INTL_IDNA_VARIANT_2003 has been removed.

  • The deprecated Normalizer::NONE constant has been removed.

LDAP

MBString

OCI8

  • The OCI-Lob class is now called OCILob, and the OCI-Collection class is now called OCICollection for name compliance enforced by PHP 8 arginfo type annotation tooling.

  • Several alias functions have been marked as deprecated.

  • oci_internal_debug() and its alias ociinternaldebug() have been removed.

ODBC

OpenSSL

Regular Expressions (Perl-Compatible)

When passing invalid escape sequences they are no longer interpreted as literals. This behavior previously required the X modifier – which is now ignored.

PHP Data Objects

  • The default error handling mode has been changed from "silent" to "exceptions". See Errors and error handling for details.

  • The signatures of some PDO methods have changed:

    • PDO::query(string $query, ?int $fetchMode = null, mixed ...$fetchModeArgs)
    • PDOStatement::setFetchMode(int $mode, mixed ...$args)

PDO ODBC

The php.ini directive pdo_odbc.db2_instance_name has been removed.

PDO MySQL

PDO::inTransaction() now reports the actual transaction state of the connection, rather than an approximation maintained by PDO. If a query that is subject to "implicit commit" is executed, PDO::inTransaction() will subsequently return false, as a transaction is no longer active.

PostgreSQL

  • The deprecated pg_connect() syntax using multiple parameters instead of a connection string is no longer supported.

  • The deprecated pg_lo_import() and pg_lo_export() signature that passes the connection as the last argument is no longer supported. The connection should be passed as first argument instead.

  • pg_fetch_all() will now return an empty array instead of false for result sets with zero rows.

Phar

Metadata associated with a phar will no longer be automatically unserialized, to fix potential security vulnerabilities due to object instantiation, autoloading, etc.

Reflection

  • The method signatures

    • ReflectionClass::newInstance($args)
    • ReflectionFunction::invoke($args)
    • ReflectionMethod::invoke($object, $args)

    have been changed to:

    • ReflectionClass::newInstance(...$args)
    • ReflectionFunction::invoke(...$args)
    • ReflectionMethod::invoke($object, ...$args)

    Code that must be compatible with both PHP 7 and PHP 8 can use the following signatures to be compatible with both versions:

    • ReflectionClass::newInstance($arg = null, ...$args)
    • ReflectionFunction::invoke($arg = null, ...$args)
    • ReflectionMethod::invoke($object, $arg = null, ...$args)

  • The ReflectionType::__toString() method will now return a complete debug representation of the type, and is no longer deprecated. In particular the result will include a nullability indicator for nullable types. The format of the return value is not stable and may change between PHP versions.

  • Reflection export() methods have been removed. Instead reflection objects can be cast to string.

  • ReflectionMethod::isConstructor() and ReflectionMethod::isDestructor() now also return true for __construct() and __destruct() methods of interfaces. Previously, this would only be true for methods of classes and traits.

  • ReflectionType::isBuiltin() method has been moved to ReflectionNamedType. ReflectionUnionType does not have it.

Sockets

  • The deprecated AI_IDN_ALLOW_UNASSIGNED and AI_IDN_USE_STD3_ASCII_RULES flags for socket_addrinfo_lookup() have been removed.

Standard PHP Library (SPL)

Standard Library

  • assert() will no longer evaluate string arguments, instead they will be treated like any other argument. assert($a == $b) should be used instead of assert('$a == $b'). The assert.quiet_eval ini directive and the ASSERT_QUIET_EVAL constant have also been removed, as they would no longer have any effect.

  • parse_str() can no longer be used without specifying a result array.

  • The string.strip_tags filter has been removed.

  • The needle argument of strpos(), strrpos(), stripos(), strripos(), strstr(), strchr(), strrchr(), and stristr() will now always be interpreted as a string. Previously non-string needles were interpreted as an ASCII code point. An explicit call to chr() can be used to restore the previous behavior.

  • The needle argument for strpos(), strrpos(), stripos(), strripos(), strstr(), stristr() and strrchr() can now be empty.

  • The length argument for substr(), substr_count(), substr_compare(), and iconv_substr() can now be null. null values will behave as if no length argument was provided and will therefore return the remainder of the string instead of an empty string.

  • The length argument for array_splice() can now be null. null values will behave identically to omitting the argument, thus removing everything from the offset to the end of the array.

  • The args argument of vsprintf(), vfprintf(), and vprintf() must now be an array. Previously any type was accepted.

  • The 'salt' option of password_hash() is no longer supported. If the 'salt' option is used a warning is generated, the provided salt is ignored, and a generated salt is used instead.

  • The quotemeta() function will now return an empty string if an empty string was passed. Previously false was returned.

  • The following functions have been removed:

  • FILTER_SANITIZE_MAGIC_QUOTES has been removed.

  • Calling implode() with parameters in a reverse order ($pieces, $glue) is no longer supported.

  • parse_url() will now distinguish absent and empty queries and fragments:

    • http://example.com/foo → query = null, fragment = null
    • http://example.com/foo? → query = "", fragment = null
    • http://example.com/foo# → query = null, fragment = ""
    • http://example.com/foo?# → query = "", fragment = ""
    Previously all cases resulted in query and fragment being null.

  • var_dump() and debug_zval_dump() will now print floating-point numbers using serialize_precision rather than precision. In a default configuration, this means that floating-point numbers are now printed with full accuracy by these debugging functions.

  • If the array returned by __sleep() contains non-existing properties, these are now silently ignored. Previously, such properties would have been serialized as if they had the value null.

  • The default locale on startup is now always "C". No locales are inherited from the environment by default. Previously, LC_ALL was set to "C", while LC_CTYPE was inherited from the environment. However, some functions did not respect the inherited locale without an explicit setlocale() call. An explicit setlocale() call is now always required if a locale component should be changed from the default.

  • The deprecated DES fallback in crypt() has been removed. If an unknown salt format is passed to crypt(), the function will fail with *0 instead of falling back to a weak DES hash now.

  • Specifying out of range rounds for SHA256/SHA512 crypt() will now fail with *0 instead of clamping to the closest limit. This matches glibc behavior.

  • The result of sorting functions may have changed, if the array contains elements that compare as equal.

  • Any functions accepting callbacks that are not explicitly specified to accept parameters by reference will now warn if a callback with reference parameters is used. Examples include array_filter() and array_reduce(). This was already the case for most, but not all, functions previously.

  • The HTTP stream wrapper as used by functions like file_get_contents() now advertises HTTP/1.1 rather than HTTP/1.0 by default. This does not change the behavior of the client, but may cause servers to respond differently. To retain the old behavior, set the 'protocol_version' stream context option, e.g.

    <?php
    $ctx 
    stream_context_create(['http' => ['protocol_version' => '1.0']]);
    echo 
    file_get_contents('http://example.org'false$ctx);
    ?>

  • Calling crypt() without an explicit salt is no longer supported. If you would like to produce a strong hash with an auto-generated salt, use password_hash() instead.

  • substr(), mb_substr(), iconv_substr() and grapheme_substr() now consistently clamp out-of-bounds offsets to the string boundary. Previously, false was returned instead of the empty string in some cases.

  • On Windows, the program execution functions (proc_open(), exec(), popen() etc.) using the shell, now consistently execute %comspec% /s /c "$commandline", which has the same effect as executing $commandline (without additional quotes).

Sysvsem

  • The auto_release parameter of sem_get() was changed to accept bool values rather than int.

Tidy

  • The use_include_path parameter, which was not used internally, has been removed from tidy_repair_string().

  • tidy::repairString() and tidy::repairFile() became static methods.

Tokenizer

  • T_COMMENT tokens will no longer include a trailing newline. The newline will instead be part of a following T_WHITESPACE token. It should be noted that T_COMMENT is not always followed by whitespace, it may also be followed by T_CLOSE_TAG or end-of-file.

  • Namespaced names are now represented using the T_NAME_QUALIFIED (Foo\Bar), T_NAME_FULLY_QUALIFIED (\Foo\Bar) and T_NAME_RELATIVE (namespace\Foo\Bar) tokens. T_NS_SEPARATOR is only used for standalone namespace separators, and only syntactially valid in conjunction with group use declarations.

XMLReader

XMLReader::open() and XMLReader::xml() are now static methods. They can still be called as instance methods, but inheriting classes need to declare them as static if they override these methods.

XML-RPC

The XML-RPC extension has been moved to PECL and is no longer part of the PHP distribution.

Zip

ZipArchive::OPSYS_Z_CPM has been removed (this name was a typo). Use ZipArchive::OPSYS_CPM instead.

Zlib

Pacotes de teste para PHP no Windows

The test runner has been renamed from run-test.php to run-tests.php, to match its name in php-src.

add a note add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top