0%

在这里可以参看原文

  • BZ2:
    • Fixed bug #71263 (fread() does not report bzip2.decompress errors).
  • CLI:
    • Allow debug server binding to an ephemeral port via `-S localhost:0`.
  • COM:
    • Fixed bug #55847 (DOTNET .NET 4.0 GAC new location).
    • Fixed bug #62474 (com_event_sink crashes on certain arguments).
  • Calendar:
    • Fixed bug #80007 (Potential type confusion in unixtojd() parameter parsing).
  • Core:
    • Fixed bug #36365 (scandir duplicates file name at every 65535th file).
    • Fixed bug #49555 (Fatal error “Function must be a string” message should be renamed).
    • Fixed bug #62294 (register_shutdown_function() does not correctly handle exit code).
    • Fixed bug #62609 (Allow implementing Traversable on abstract classes).
    • Fixed bug #65274 (Enhance undefined class constant error with class name).
    • Fixed bug #65275 (Calling exit() in a shutdown function does not change the exit value in CLI).
    • Fixed bug #69084 (Unclear error message when not implementing a renamed abstract trait function).
    • Fixed bug #70839 (Converting optional argument to variadic forbidden by LSP checks).
    • Fixed bug #74558 (Can’t rebind closure returned by Closure::fromCallable()).
    • Fixed bug #77561 (Shebang line not stripped for non-primary script).
    • Fixed bug #77619 (Wrong reflection on MultipleIterator::__construct).
    • Fixed bug #77966 (Cannot alias a method named “namespace”).
    • Fixed bug #78236 (convert error on receiving variables when duplicate [).
    • Fixed bug #78770 (Incorrect callability check inside internal methods).
    • Fixed bug #79108 (Referencing argument in a function makes it a reference in the stack trace).
    • Fixed bug #79368 (“Unexpected end of file” is not an acceptable error message).
    • Fixed bug #79462 (method_exists and property_exists incoherent behavior).
    • Fixed bug #79467 (data:// wrappers are writable).
    • Fixed bug #79521 (Check __set_state structure).
    • Fixed bug #79790 (“Illegal offset type” exception during AST evaluation not handled properly).
    • Fixed bug #79791 (Assertion failure when unsetting variable during binary op).
    • Fixed bug #79828 (Segfault when trying to access non-existing variable).
    • Fixed bug #79841 (Syntax error in configure / unescaped “[]” in php.m4).
    • Fixed bug #79852 (count(DOMNodeList) doesn’t match count(IteratorIterator(DOMNodeList))).
    • Fixed bug #79867 (Promoted untyped properties should get null default value).
    • Fixed bug #79897 (Promoted constructor params with attribs cause crash).
    • Fixed bug #79927 (Generator doesn’t throw exception after multiple yield from iterable).
    • Fixed bug #79946 (Build fails due to undeclared UINT32_C).
    • Fixed bug #79948 (Exit in auto-prepended file does not abort PHP execution).
    • Fixed bug #80045 (memleak after two set_exception_handler calls with __call).
    • Fixed bug #80096 (Segmentation fault with named arguments in nested call).
    • Fixed bug #80109 (Cannot skip arguments when extended debug is enabled).
    • Fixed bug #80225 (broken namespace usage in eval code).
    • Fixed bug #80258 (Windows Deduplication Enabled, randon permission errors).
    • Fixed bug #80280 (ADD_EXTENSION_DEP() fails for ext/standard and ext/date).
    • Fixed bug #80334 (assert() vs named parameters - confusing error).
    • Fixed bug #80055 (Abstract trait methods returning “self” cannot be fulfilled by traits).
    • Fixed faulty generator cleanup with yield from.
    • Implement #[Attr] Attribute syntax as per final vote in RFC https://wiki.php.net/rfc/shorter_attribute_syntax_change
    • Implemented FR #47074 (phpinfo() reports “On” as 1 for the some extensions).
    • Implemented FR #72089 (require() throws fatal error instead of exception).
    • Removed the pdo_odbc.db2_instance_name php.ini directive.
    • Use SSE2 instructions do locale independent strtolower.
    • How ?
  • Curl:
    • Bumped required libcurl version to 7.29.0.
    • Fixed bug #80121 (Null pointer deref if CurlHandle directly instantiated).
  • DOM:
    • Add property DOMXPath::$registerNodeNamespaces and constructor argument that allow global flag to configure query() or evaluate() calls.
    • Fixed bug #79968 (DOMChildNode API crash on unattached nodes).
    • Fixed bug #80268 (loadHTML() truncates at NUL bytes).
  • Date:
    • Fixed bug #60302 (DateTime::createFromFormat should new static(), not new self()).
    • Fixed bug #65547 (Default value for sunrise/sunset zenith still wrong).
    • Fixed bug #69044 (discrepancy between time and microtime).
    • Fixed bug #80057 (DateTimeImmutable::createFromFormat() does not populate time).
    • Implemented FR #79903 (datetime: new format “p”, same as “P” but returning “Z” for UTC).
  • Enchant:
    • Add LIBENCHANT_VERSION macro.
    • Add enchant_dict_add and enchant_dict_is_added functions.
    • Deprecate enchant_broker_set_dict_path, enchant_broker_get_dict_path, enchant_dict_add_to_personal and enchant_dict_is_in_session.
    • Use libenchant-2 when available.
  • FFI:
    • Added FFI\CType::getName() method.
    • Fixed bug #79177 (FFI doesn’t handle well PHP exceptions within callback).
    • Fixed bug #79749 (Converting FFI instances to bool fails).
  • FPM:
    • Add pm.status_listen option.
  • Fileinfo:
    • Upgrade to libmagic 5.39.
  • GD:
    • Added imagegetinterpolation().
    • Fixed bug #55005 (imagepolygon num_points requirement).
    • Made the $num_points parameter of php_imagepolygon optional.
    • Removed deprecated image2wbmp().
    • Removed deprecated png2wbmp() and jpeg2wbmp().
    • Replaced gd resources with objects.
  • IMAP:
    • Fixed bug #64076 (imap_sort() does not return FALSE on failure).
    • Fixed bug #76618 (segfault on imap_reopen).
    • Fixed bug #80213 (imap_mail_compose() segfaults on certain $bodies).
    • Fixed bug #80215 (imap_mail_compose() may modify by-val parameters).
    • Fixed bug #80216 (imap_mail_compose() does not validate types/encodings).
    • Fixed bug #80220 (imap_mail_compose() may leak memory).
    • Fixed bug #80223 (imap_mail_compose() leaks envelope on malformed bodies).
    • Fixed bug #80226 (imap_sort() leaks sortpgm memory).
    • Fixed bug #80239 (imap_rfc822_write_address() leaks memory).
    • Fixed bug #80242 (imap_mail_compose() segfaults for multipart with rfc822).
    • Fixed minor regression caused by fixing bug #80220.
  • Iconv:
    • Dropped support for iconv without proper errno setting.
  • Intl:
    • Removed deprecated INTL_IDNA_VARIANT_2003.
  • JIT:
    • Fixed bug #77857 (Wrong result if executed with JIT).
    • Fixed bug #79255 (PHP cannot be compiled with enable JIT).
    • Fixed bug #79582 (Crash seen when opcache.jit=1235 and opcache.jit_debug=2).
    • Fixed bug #79743 (Fatal error when assigning to array property with JIT enabled).
    • Fixed bug #79864 (JIT segfault in Symfony OptionsResolver).
    • Fixed bug #79888 (Incorrect execution with JIT enabled).
  • JSON:
  • LDAP:
    • Fixed memory leaks.
    • Removed deprecated ldap_sort.
  • MBString:
    • Fixed bug #76999 (mb_regex_set_options() return current options).
    • Removed the unused $is_hex parameter from mb_decode_numericentity().
  • MySQLi:
    • Fixed bug #76809 (SSL settings aren’t respected when persistent connections are used).
  • Mysqlnd:
    • Fixed bug #60594 (mysqlnd exposes 160 lines of stats in phpinfo).
  • OCI8:
    • Deprecated old OCI8 function aliases.
    • Modernized oci_register_taf_callback() callable argument parsing implementation.
    • Removed obsolete no-op function oci_internal_debug().
  • ODBC:
    • Fixed bug #22986 (odbc_connect() may reuse persistent connection).
    • Fixed bug #44618 (Fetching may rely on uninitialized data).
  • Opcache:
    • Fixed bug #76535 (Opcache does not replay compile-time warnings).
    • Fixed bug #78654 (Incorrectly computed opcache checksum on files with non-ascii characters).
    • Fixed bug #79665 (ini_get() and opcache_get_configuration() inconsistency).
    • Fixed bug #80030 (Optimizer segfault with isset on static property with undef dynamic class name).
    • Fixed bug #80175 (PHP8 RC1 - JIT Buffer not working).
    • Fixed bug #80184 (Complex expression in while / if statements resolves to false incorrectly).
    • Fixed bug #80255 (Opcache bug (bad condition result) in 8.0.0rc1).
    • Fixed run-time binding of preloaded dynamically declared function.
  • OpenSSL:
    • Added Cryptographic Message Syntax (CMS) support.
  • PCRE:
    • Don’t ignore invalid escape sequences.
    • Updated to PCRE2 10.35.
  • PDO:
    • Changed default PDO error mode to exceptions.
    • Fixed bug #77849 (Disable cloning of PDO handle/connection objects).
  • PDO_Firebird:
    • Fixed bug #64937 (Firebird PDO preprocessing sql).
  • PDO_OCI:
    • Added support for setting and getting the oracle OCI 18c call timeout.
  • PDO_PGSQL:
    • Bumped required libpq version to 9.1.
  • PGSQL:
    • Bumped required libpq version to 9.1.
  • Phpdbg:
    • Fixed bug #76596 (phpdbg support for display_errors=stderr).
    • Fixed bug #76801 (too many open files).
    • Fixed bug #77800 (phpdbg segfaults on listing some conditional breakpoints).
    • Fixed bug #77805 (phpdbg build fails when readline is shared).
  • Reflection:
    • Fixed bug #64592 (ReflectionClass::getMethods() returns methods out of scope).
    • Fixed bug #69180 (Reflection does not honor trait conflict resolution / method aliasing).
    • Fixed bug #74939 (Nested traits’ aliased methods are lowercased).
    • Fixed bug #77325 (ReflectionClassConstant::$class returns wrong class when extending).
    • Fixed bug #78697 (ReflectionClass::implementsInterface - inaccurate error message with traits).
    • Fixed bug #80190 (ReflectionMethod::getReturnType() does not handle static as part of union type).
    • Fixed bug #80299 (ReflectionFunction->invokeArgs confused in arguments).
    • Fixed bug #80370 (getAttributes segfault on dynamic properties).
    • Implemented FR #79628 (Add $filter parameter for ReflectionClass::getConstants and ReflectionClass::getReflectionConstants) (carusogabriel)
    • Implement ReflectionProperty::hasDefaultValue and Reflection::getDefaultValue (beberlei)
  • SNMP:
    • Fixed bug #70461 (disable md5 code when it is not supported in net-snmp).
  • SPL:
    • Fixed bug #65006 (spl_autoload_register fails with multiple callables using self, same method).
    • Fixed bug #65387 (Circular references in SPL iterators are not garbage collected).
    • Fixed bug #71236 (Second call of spl_autoload_register() does nothing if it has no arguments).
    • Fixed bug #79987 (Memory leak in SplFileInfo because of missing zend_restore_error_handling()).
    • SplFixedArray is now IteratorAggregate rather than Iterator.
  • SQLite3:
    • Added SQLite3::setAuthorizer() and respective class constants.
  • Session:
    • Fixed bug #73529 (session_decode() silently fails on wrong input).
    • Fixed bug #78624 (session_gc return value for user defined session handlers).
  • Shmop:
    • Converted shmop resources to objects.
  • SimpleXML:
    • Fixed bug #63575 (Root elements are not properly cloned).
    • Fixed bug #75245 (Don’t set content of elements with only whitespaces).
  • Sodium:
    • Fixed bug #77646 (sign_detached() strings not terminated).
  • Standard:
    • Don’t force rebuild of symbol table, when populating $http_response_header variable by the HTTP stream wrapper.
    • Fixed bug #47983 (mixed LF and CRLF line endings in mail()).
    • Fixed bug #64060 (lstat_stat_variation7.phpt fails on certain file systems).
    • Fixed bug #75902 (str_replace should warn when misused with nested arrays).
    • Fixed bug #76859 (stream_get_line skips data if used with data-generating filter).
    • Fixed bug #77204 (getimagesize(): Read error! should mention file path).
    • Fixed bug #78385 (parse_url() does not include ‘query’ when question mark is the last char).
    • Fixed bug #79868 (Sorting with array_unique gives unwanted result).
    • Fixed bug #80256 (file_get_contents strip first line with chunked encoding redirect).
    • Fixed bug #80266 (parse_url silently drops port number 0).
    • Fixed bug #80290 (Double free when ASSERT_CALLBACK is used with a dynamic message).
    • Implemented FR #78638 (__PHP_Incomplete_Class should be final).
    • Made quoting of cmd execution functions consistent.
  • Tidy:
    • Removed the unused $use_include_path parameter from tidy_repair_string().
  • Tokenizer:
    • Fixed bug #80328 (PhpToken::getAll() confusing name).
  • XML:
    • Fixed bug #76874 (xml_parser_free() should never leak memory).
  • XMLWriter:
    • Changed functions to accept/return XMLWriter objects instead of resources.
    • Implemented FR #79344 (xmlwriter_write_attribute_ns: $prefix should be nullable).
    • Removed return types from XMLWriter stubs.
  • Zip:
    • Add “flags” options to ZipArchive::addGlob and addPattern methods keeping previous behavior having FL_OVERWRITE by default.
    • Add ZipArchive::EM_UNKNOWN and ZipArchive::EM_TRAD_PKWARE constants.
    • Add ZipArchive::isCompressionMethodSupported() and ZipArchive::isEncryptionMethodSupported() method (libzip 1.7.0).
    • Add ZipArchive::replaceFile() method.
    • Add ZipArchive::setCancelCallback method (since libzip 1.6.0).
    • Add ZipArchive::setMtimeName and ZipArchive::setMtimeIndex methods.
    • Add ZipArchive::setProgressCallback method (since libzip 1.3.0).
    • Add lastId property to ZipArchive.
    • Add optional “flags” parameter to ZipArchive::addEmptyDir, addFile and addFromString methods.
    • Fixed bug #50678 (files extracted by ZipArchive class lost their original modified time).
    • Fixed bug #72374 (remove_path strips first char of filename).
    • Implemented FR #77960 (add compression / encryption options for ZipArchive::addGlob and ZipArchive::addPattern).
    • ZipArchive::status and ZipArchive::statusSys properties and ZipArchive::getStatusString() method stay valid after the archive is closed.
  • Zlib:
    • Fixed bug #71417 (fread() does not report zlib.inflate errors).
    • Fixed bug #78792 (zlib.output_compression disabled by Content-Type: image/).
阅读全文 »

目标及关键路径

https://www.php.net/releases/8.0/zh.php

  • 提升性能
    • 基于缓存前置思想,使用CPU机器码缓存,绕过Zend VM及其过程开销来尽可能提升性能
      • JIT

从 PHP 7.4.x 移植到 PHP 8.0.x

PHP 8.0: What’s New and Changed
PHP Manual

不向后兼容的变更

PHP Core

  • 字符串与数字的比较

    • v8.0.0 数字与非数字形式的字符串之间的非严格比较现在将首先将数字转为字符串,然后比较这两个字符串。 数字与数字形式的字符串之间的比较仍然像之前那样进行。 请注意,这意味着 0 == “not-a-number” 现在将被认为是 false 。

      Comparison Before After
      0 == "0" true true
      0 == "0.0" true true
      0 == "foo" true false
      0 == "" true false
      42 == " 42" true true
      42 == "42foo" true false
  • v8.0.0 match 现在是一个保留字。

    PHP RFC: Match expression v2

  • v8.0.0 断言(Assertion)失败现在默认抛出异常。如果想要改回之前的行为,可以在 INI 设置中设置 assert.exception=0

  • 8.0.0 与类名相同的方法名将不再被当做构造方法。应该使用__construct() 来取代它。

  • 8.0.0 不再允许通过静态调用的方式去调用非静态方法。因此is_callable()在检查一个类名与非静态方法 时将返回失败(应当检查一个类的实例)。

  • v8.0.0 (real)(unset) 转换已被移除。

  • v8.0.0 The track_errors ini directive has been removed. This means that php_errormsg is no longer available. The error_get_last() function may be used instead.

  • v8.0.0 The ability to define case-insensitive constants has been removed. The third argument to define() may no longer be true.

  • v8.0.0 The ability to specify an autoloader using an __autoload() function has been removed. spl_autoload_register() should be used instead.

  • v8.0.0 The errcontext argument will no longer be passed to custom error handlers set with set_error_handler().

  • v8.0.0 create_function() has been removed. Anonymous functions may be used instead.

  • v8.0.0 each() has been removed. foreach or ArrayIterator should be used instead.

  • v8.0.0 The ability to unbind this from closures that were created from a method, using Closure::fromCallable() or ReflectionMethod::getClosure(), has been removed.

  • v8.0.0 The ability to unbind this from proper closures that contain uses of this has also been removed.

  • v8.0.0 The ability to use array_key_exists() with objects has been removed. isset() or property_exists() may be used instead.

  • v8.0.0 The behavior of array_key_exists() regarding the type of the key parameter has been made consistent with isset() and normal array access. All key types now use the usual coercions and array/object keys throw a TypeError.

  • v8.0.0 Any array that has a number n as its first numeric key will use n+1 for its next implicit key, even if n is negative.

    PHP RFC: Arrays starting with a negative index
    PHP 8.0: Implicit negative array key increments do not skip negative numbers

  • v8.0.0 The default error_reporting level is now E_ALL. Previously it excluded E_NOTICE and E_DEPRECATED.

  • v8.0.0 display_startup_errors is now enabled by default.

  • v8.0.0 Using parent inside a class that has no parent will now result in a fatal compile-time error.

  • v8.0.0 The @ operator will no longer silence fatal errors (E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR, E_PARSE). Error handlers that expect error_reporting to be 0 when @ is used, should be adjusted to use a mask check instead:

    <?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
        }
        // ...
    }
    ?>
    

    Additionally, care should be taken that error messages are not displayed in production environments, which can result in information leaks. Please ensure that display_errors=Off is used in conjunction with error logging.

    PHP 8.0: @ Error Suppression operator does not silent fatal errors

  • v8.0.0 #[ is no longer interpreted as the start of a comment, as this syntax is now used for attributes.

    PHP RFC: Attributes v2
    Discussion: Attributes v2
    PHP 8.0: Attributes

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

    PHP RFC: Always generate fatal error for incompatible method signatures
    Github Pull Request: Always generate fatal error for LSP failures #4000
    PHP 8.0: Fatal errors on incompatible method signatures

  • v7.4.0 The precedence of the concatenation operator has changed relative to bitshifts and addition as well as subtraction.

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

    PHP RFC: Change the precedence of the concatenation operator
    PHP 8.0: +/- operators take higher precedence when used with concat (.) operator

  • v8.0.0 Arguments with a default value that resolves to null at runtime will no longer implicitly mark the argument type as nullable. Either an explicit nullable type, or an explicit null default value has to be used instead.

    <?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) {}
    ?>
    

    Github Pull Request: Don’t make argument nullable based on AST null initializer #4720

  • v8.0.0 A number of warnings have been converted into Error exceptions:

    PHP RFC: Reclassifying engine warnings

    • 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.

    A number of notices have been converted into warnings:

    • Attempting to read an undefined variable.
    • Attempting to read an undefined property.
    • Attempting to read an undefined array key.
    • Attempting to read a property of a non-object.
    • Attempting to access an array index of a non-array.
    • Attempting to convert an array to string.
    • Attempting to use a resource as an array key.
    • Attempting to use null, a boolean, or a float as a string offset.
    • Attempting to read an out-of-bounds string offset.
    • Attempting to assign an empty string to a string offset.
  • v8.0.0 Attempting to assign multiple bytes to a string offset will now emit a warning.

  • v8.0.0 Unexpected characters in source files (such as NUL bytes outside of strings) will now result in a ParseError exception instead of a compile warning.

    Github Pull Request: Replace “unexpected character” warning with ParseError #4767

  • v8.0.0 Uncaught exceptions now go through “clean shutdown”, which means that destructors will be called after an uncaught exception.

  • v8.0.0 The compile time fatal error “Only variables can be passed by reference” has been delayed until runtime, and converted into an “Argument cannot be passed by reference” Error exception.

  • v8.0.0 Some “Only variables should be passed by reference” notices have been converted to “Argument cannot be passed by reference” exception.

  • v8.0.0 The generated name for anonymous classes has changed. It will now include the name of the first parent or interface:

    <?php
    new class extends ParentClass {};
    // -> [email protected]
    new class implements FirstInterface, SecondInterface {};
    // -> [email protected]
    new class {};
    // -> [email protected]
    ?>
    

    The name shown above is still followed by a NUL byte and a unique suffix.

    Github Pull Request: Improve generated names for anonymous classes #5153

  • v8.0.0 Non-absolute trait method references in trait alias adaptations are now required to be unambiguous:

    <?php
    class X {
        use T1, T2 {
            func as otherFunc;
        }
        function func() {}
    }
    ?>
    

    If both T1::func() and T2::func() exist, this code was previously silently accepted, and func was assumed to refer to T1::func. Now it will generate a fatal error instead, and either T1::func or T2::func needs to be written explicitly.

    Github Pull Request: Require non-absolute trait method refs to be unambiguous #5232

  • v8.0.0 The signature of abstract methods defined in traits is now checked against the implementing class method:

    
    <?php
    trait MyTrait {
        abstract private function neededByTrait(): string;
    }
    
    class MyClass {
        use MyTrait;
    
        // Error, because of return type mismatch.
        private function neededByTrait(): int { return 42; }
    }
    ?>
    

    PHP RFC: Validation for abstract trait methods
    Github Pull Request: Check abstract method signatures coming from traits #5068

  • v8.0.0 Disabled functions are now treated exactly like non-existent functions. Calling a disabled function will report it as unknown, and redefining a disabled function is now possible.

    Github Pull Request: Completely remove disabled functions from function table #5473

  • v8.0.0 data:// stream wrappers are no longer writable, which matches the documented behavior.

  • v8.0.0 The arithmetic and bitwise operators +, -, *, /, **, %, <<, >>, &, |, ^, ~, ++, -- will now consistently throw a TypeError when one of the operands is an array, 资源(resource) or non-overloaded object. The only exception to this is the array + array merge operation, which remains supported.

    PHP RFC: Stricter type checks for arithmetic/bitwise operators
    Github Pull Request: Make numeric operations on resources, arrays and objects type errors #5331

  • v8.0.0 Float to string casting will now always behave locale-independently.

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

    See printf(), number_format() and NumberFormatter() for ways to customize number formatting.

    PHP RFC: Locale-independent float to string cast
    Github Pull Request: Make float to string conversions locale-independent #5224

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

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

    PHP RFC: Deprecate curly brace syntax for accessing array elements and string offsets
    Github Pull Request: Deprecate curly brace syntax for array/string offset access #4416

  • Applying the final modifier on a private method will now produce a warning unless that method is the constructor.

  • If an object constructor exit()s, the object destructor will no longer be called. This matches the behavior when the constructor throws.

  • Namespaced names can no longer contain whitespace: While Foo\Bar will be recognized as a namespaced name, Foo \ Bar will not. Conversely, reserved keywords are now permitted as namespace segments, which may also change the interpretation of code: new\x is now the same as constant('new\x'), not new \x().

  • Nested ternaries now require explicit parentheses.

  • debug_backtrace() and Exception::getTrace() will no longer provide references to arguments. It will not be possible to change function arguments through the backtrace.

  • Numeric string handling has been altered to be more intuitive and less error-prone. Trailing whitespace is now allowed in numeric strings for consistency with how leading whitespace is treated. This mostly affects:

    • The is_numeric() function
    • String-to-string comparisons
    • Type declarations
    • Increment and decrement operations

    The concept of a “leading-numeric string” has been mostly dropped; the cases where this remains exist in order to ease migration. Strings which emitted an E_NOTICE “A non well-formed numeric value encountered” will now emit an E_WARNING “A non-numeric value encountered” and all strings which emitted an E_WARNING “A non-numeric value encountered” will now throw a TypeError. This mostly affects:

    • Arithmetic operations
    • Bitwise operations

    This E_WARNING to TypeError change also affects the E_WARNING “Illegal string offset ‘string’” for illegal string offsets. The behavior of explicit casts to int/float from strings has not been changed.

  • Magic Methods will now have their arguments and return types checked if they have them declared. The signatures should match the following list:

    • __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
  • call_user_func_array() array keys will now be interpreted as parameter names, instead of being silently ignored.

  • Declaring a function called assert() inside a namespace is no longer allowed, and issues E_COMPILE_ERROR. 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.

  • 如果带有默认值的参数后面跟着一个必要的参数,那么默认值就会无效。这在 PHP 8.0.0 中已被废弃,通常可以通过删除默认值,不影响现有功能:

    <?php
    function test($a = [], $b) {} // 之前
    function test($a, $b) {}      // 之后
    ?>
    

    这条规则的一个例外是 Type $param = null 形式的参数,其中 null 的默认值使得类型隐式为空。这种用法仍然是允许的,但仍建议使用显式可空类型。

    <?php
    function test(A $a = null, $b) {} // 旧写法,仍可用
    function test(?A $a, $b) {}       // 推荐写法
    ?>
    
  • 参数 exclude_disabled 不能设置为 false 来调用 get_defined_functions(),该参数已被废弃,不再起作用。 get_defined_functions() 绝不会再包含禁用的函数。

Resource to Object Migration

Several 资源(resource)s have been migrated to objects. Return value checks using is_resource() should be replaced with checks for false.

阅读全文 »

目标及关键路径

  • 性能提升

从 PHP 7.3.x 移植到 PHP 7.4.x

这里可以找到原文

不向下兼容的变更

  • 尝试以数组方式访问 null,bool, int,float 或 resource (例如 $null[“key”])将会抛出 notice 通知。

  • get_declared_classes() 函数将不再返回匿名的类,假如它们没有被实例化的话。

  • fn 成为了保留关键词

  • 文件尾部的 <?php 标签(不包含空行)将会被解释成一个 PHP 头标签。

  • When using include/require on a stream, streamWrapper::stream_set_option() will be invoked with the STREAM_OPTION_READ_BUFFER option.

  • 序列化类型 o 被移除。因为它不是由 PHP 生成的,这可能会影响到之前项目中手动生成的序列化字符串。

  • 密码哈希算法标识符现在是可空字符串,而不再是整数。

    • PASSWORD_DEFAULT 之前是 int 1; 现在是 null
    • PASSWORD_BCRYPT 之前是 int 1; 现在是 string ‘2y’
    • PASSWORD_ARGON2I 之前是 int 2; 现在是 string ‘argon2i’
    • PASSWORD_ARGON2ID 之前是 int 3; 现在是 string ‘argon2id’
  • htmlentities() will now raise a notice (instead of a strict standards warning) if it is used with an encoding for which only basic entity substitution is supported, in which case it is equivalent to htmlspecialchars().

  • fread()fwrite() 在操作失败的时候会返回 false

  • BCMath functions will now warn if a non well-formed number is passed, such as “32foo”.

  • CURL

    • Attempting to serialize a CURLFile class will now generate an exception. Previously the exception was only thrown on unserialization.
    • Using CURLPIPE_HTTP1 is deprecated, and is no longer supported as of cURL 7.62.0.
    • The $version parameter of curl_version() is deprecated. If any value not equal to the default CURLVERSION_NOW is passed, a warning is raised and the parameter is ignored.
  • Date and Time

    • Calling var_dump() or similar on a DateTime or DateTimeImmutable instance will no longer leave behind accessible properties on the object.

    • Comparison of DateInterval objects (using ==, <, and so on) will now generate a warning and always return false. Previously all DateInterval objects were considered equal, unless they had properties.

  • The default parameter value of idn_to_ascii() and idn_to_utf8() is now INTL_IDNA_VARIANT_UTS46 instead of the deprecated INTL_IDNA_VARIANT_2003.

  • MySQLi

    • The embedded server functionality has been removed. It was broken since at least PHP 7.0.
    • The undocumented mysqli::$stat property has been removed in favor of mysqli::stat().
  • The openssl_random_pseudo_bytes() function will now throw an exception in error situations, similar to random_bytes(). In particular, an Error is thrown if the number of requested bytes is less than or equal to zero, and an Exception is thrown if sufficient randomness cannot be gathered. The $crypto_strong output argument is guaranteed to always be true if the function does not throw, so explicitly checking it is not necessary.

  • When PREG_UNMATCHED_AS_NULL mode is used, trailing unmatched capturing groups will now also be set to null (or [null, -1] if offset capture is enabled). This means that the size of the $matches will always be the same.

  • Attempting to serialize a PDO or PDOStatement instance will now generate an Exception rather than a PDOException, consistent with other internal classes which do not support serialization.

  • Reflection objects will now generate an exception if an attempt is made to serialize them. Serialization for reflection objects was never supported and resulted in corrupted reflection objects. It has been explicitly prohibited now.

  • Standard PHP Library (SPL)

    • Calling get_object_vars() on an ArrayObject instance will now always return the properties of the ArrayObject itself (or a subclass). Other affected operations are:

      • ReflectionObject::getProperties()
      • reset(), current(), etc. Use Iterator methods instead.
      • Potentially others working on object properties as a list.
    • SplPriorityQueue::setExtractFlags() will throw an exception if zero is passed. Previously this would generate a recoverable fatal error on the next extraction operation.

    • ArrayObject, ArrayIterator, SplDoublyLinkedList and SplObjectStorage now support the __serialize() and __unserialize() mechanism in addition to the Serializable interface. This means that serialization payloads created on older PHP versions can still be unserialized, but new payloads created by PHP 7.4 will not be understood by older versions.

  • token_get_all() will now emit a T_BAD_CHARACTER token for unexpected characters instead of leaving behind holes in the token stream.

  • 从 PHP 7.4.11 开始,为了安全考虑,接受到的 Cookie 中的 names 参数不再被 URL 编码。


  • 嵌套的三元操作中,必须明确使用显式括号来决定操作的顺序。

  • 使用大括号访问数组及字符串索引的方式已被废弃。请使用 $var[$idx] 的语法来替代 $var{$idx}。

  • (real) 类型已被废弃,请使用 (float) 来替代。

  • 同时被废弃的还有 is_real() 函数,请使用 is_float() 来替代。

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

  • 在没有父类的类中使用 parent 关键词已被废弃,并且在将来的 PHP 版本中将会抛出一个编译错误。目前只在运行时访问父类时才会产生错误。

  • 配置文件中的 allow_url_include 选项被废弃。如果启用了该选项,将会产生一个弃用通知。

  • 在下面这些基础转换函数中,base_convert(), bindec(), octdec()hexdec() 如果传入了非法字符,将会抛出一个弃用通知。函数会忽略掉无效字符后正常返回结果。前导空格和尾部空格,以及类型为 0x (取决于基数) 被允许传入。

  • 在一个对象中使用 array_key_exists() 已被废弃。请使用 isset()property_exists() 来替代。

  • 魔术引号函数 get_magic_quotes_gpc()get_magic_quotes_runtime() 已被废弃。它们将永远返回 false

  • hebrevc() 函数已被废弃。 可以用 nl2br(hebrev($str)) 来替代,更好的方法是启用 Unicode RTL 来支持。

  • convert_cyr_string() 函数已被废弃。可以用 mb_convert_string()iconv()UConverter 替代。

  • money_format() 函数已被废弃。 可以用更国际化的 NumberFormatter 功能来替代。

  • ezmlm_hash() 函数已被废弃。

  • restore_include_path() 函数已被废弃。可以用 ini_restore('include_path') 替代。

  • implode() 允许反转参数顺序的特性已被废弃,请使用 implode($glue, $parts) 来替代 implode($parts, $glue)

  • COM, 导入类型库的大小写不敏感的常量注册已被废弃。

  • FILTER_SANITIZE_MAGIC_QUOTES 已被废弃,使用 FILTER_SANITIZE_ADD_SLASHES 来替代。

  • 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.

  • ldap_control_paged_result_response()ldap_control_paged_result() 函数已被废弃。控制页面操作可以使用 ldap_search() 替代。

  • Reflection

    • 调用 ReflectionType::__toString() 现在将会抛出一个弃用通知。 该方法从 PHP 7.1 开始,在 ReflectionNamedType::getName() 的文档中已经被声明废弃,但是由于技术原因,并没有抛出弃用通知。

    • The export() methods on all Reflection classes are deprecated.

  • 常量 AI_IDN_ALLOW_UNASSIGNEDAI_IDN_USE_STD3_ASCII_RULESsocket_addrinfo_lookup() 中不再可用,因为该常量在 glibc 中已被废弃。

  • 这些扩展已经被转移到 PECL 中,不再是 PHP 发行版的一部分。这些扩展的 PECL 包版本将根据用户的需要来自行安装。

新特性

  • 类的属性中现在支持添加指定的类型。

  • 箭头函数 提供了一种更简洁的定义函数的方法。

  • 有限返回类型协变与参数类型逆变

  • 空合并运算符赋值

  • 数组展开操作

  • 数字文字可以在数字之间包含下划线。

  • Weak references allow the programmer to retain a reference to an object that does not prevent the object from being destroyed.

  • 现在允许从 __toString() 抛出异常。之前的版本,将会导致一个致命错误。新版本中,之前发生致命错误的代码,已经被转换为 Error 异常。

  • CURLFile now supports stream wrappers in addition to plain file names, if the extension has been built against libcurl >= 7.56.0.

  • The FILTER_VALIDATE_FLOAT filter now supports the min_range and max_range options, with the same semantics as FILTER_VALIDATE_INT.

  • FFI is a new extension, which provides a simple way to call native functions, access native variables, and create/access data structures defined in C libraries.

  • Added the IMG_FILTER_SCATTER image filter to apply a scatter filter to images.

  • Added crc32c hash using Castagnoli’s polynomial. This CRC32 variant is used by storage systems, such as iSCSI, SCTP, Btrfs and ext4.

  • Added the mb_str_split() function, which provides the same functionality as str_split(), but operating on code points rather than bytes.

  • 新增 缓存预加载 特性。

  • The preg_replace_callback() and preg_replace_callback_array() functions now accept an additional flags argument, with support for the PREG_OFFSET_CAPTURE and PREG_UNMATCHED_AS_NULL flags. This influences the format of the matches array passed to to the callback function.

  • PDO

    • The username and password can now be specified as part of the PDO DSN for the mysql, mssql, sybase, dblib, firebird and oci drivers. Previously this was only supported by the pgsql driver. If a username/password is specified both in the constructor and the DSN, the constructor takes precedence.

    • It is now possible to escape question marks in SQL queries to avoid them being interpreted as parameter placeholders. Writing ?? allows sending a single question mark to the database and e.g. use the PostgreSQL JSON key exists (?) operator.

  • PDOStatement::getColumnMeta() is now available.

  • PDO_SQLite

    • PDOStatement::getAttribute(PDO::SQLITE_ATTR_READONLY_STATEMENT) allows checking whether the statement is read-only, i.e. if it doesn’t modify the database.

    • PDO::setAttribute(PDO::SQLITE_ATTR_EXTENDED_RESULT_CODES, true) enables the use of SQLite3 extended result codes in PDO::errorInfo() and PDOStatement::errorInfo().

  • SQLite3

    • Added SQLite3::lastExtendedErrorCode() to fetch the last extended result code.

    • Added SQLite3::enableExtendedResultCodes($enable = true), which will make SQLite3::lastErrorCode() return extended result codes.

  • Standard

    • strip_tags() now also accepts an array of allowed tags: instead of strip_tags($str, '<a><p>') you can now write strip_tags($str, ['a', 'p']).

    • A new mechanism for custom object serialization has been added, which uses two new magic methods: __serialize and __unserialize.

    • array_merge() and array_merge_recursive() may now be called without any arguments, in which case they will return an empty array. This is useful in conjunction with the spread operator, e.g. array_merge(...$arrays).

    • proc_open() function

      • proc_open() now accepts an array instead of a string for the command.
      • proc_open() now supports redirect and null descriptors.
    • password_hash() now has the argon2i and argon2id implementations from the sodium extension when PHP is built without libargon.

阅读全文 »

目标及关键路径

  • 性能提升

从 PHP 7.2.x 移植到 PHP 7.3.x

这里可以找到原文

不向下兼容的变更

  • Due to the introduction of flexible heredoc/nowdoc syntax, doc strings that contain the ending label inside their body may cause syntax errors or change in interpretation.

  • Continue Targeting Switch issues Warning. continue statements targeting switch control flow structures will now generate a warning. In PHP such continue statements are equivalent to break, while they behave as continue 2 in other languages.

  • Strict Interpretation of Integer String Keys on ArrayAccess. Array accesses of type $obj["123"], where $obj implements ArrayAccess and "123" is an integer string literal will no longer result in an implicit conversion to integer, i.e., $obj->offsetGet("123") will be called instead of $obj->offsetGet(123). This matches existing behavior for non-literals. The behavior of arrays is not affected in any way, they continue to implicitly convert integral string keys to integers.

  • In PHP, static properties are shared between inheriting classes, unless the static property is explicitly overridden in a child class. However, due to an implementation artifact it was possible to separate the static properties by assigning a reference. This loophole has been fixed.

  • References returned by array and property accesses are now unwrapped as part of the access. This means that it is no longer possible to modify the reference between the access and the use of the accessed value.

  • Argument unpacking stopped working with Traversables with non-integer keys. The following code worked in PHP 5.6-7.2 by accident.

  • The ext_skel utility has been completely redesigned with new options and some old options removed. This is now written in PHP and has no external dependencies.

  • Exceptions thrown due to automatic conversion of warnings into exceptions in EH_THROW mode (e.g. some DateTime exceptions) no longer populate error_get_last() state. As such, they now work the same way as manually thrown exceptions.

  • TypeError now reports wrong types as int and bool instead of integer and boolean, respectively.

  • Undefined variables passed to compact() will now be reported as a notice.

  • getimagesize() and related functions now report the mime type of BMP images as image/bmp instead of image/x-ms-bmp, since the former has been registered with the IANA (see » RFC 7903).

  • stream_socket_get_name() will now return IPv6 addresses wrapped in brackets. For example "[::1]:1337" will be returned instead of "::1:1337".

  • Support for BeOS has been dropped.

  • BCMath Arbitrary Precision Mathematics

    • All warnings thrown by BCMath functions are now using PHP’s error handling. Formerly some warnings have directly been written to stderr.

    • bcmul() and bcpow() now return numbers with the requested scale. Formerly, the returned numbers may have omitted trailing decimal zeroes.

  • IMAP, POP3 and NNTP. rsh/ssh logins are disabled by default. Use imap.enable_insecure_rsh if you want to enable them. Note that the IMAP library does not filter mailbox names before passing them to the rsh/ssh command, thus passing untrusted data to this function with rsh/ssh enabled is insecure.

  • Due to added support for named captures, mb_ereg_*() patterns using named captures will behave differently. In particular named captures will be part of matches and mb_ereg_replace() will interpret additional syntax. See Named Captures for more information.

  • MySQL Improved Extension. Prepared statements now properly report the fractional seconds for DATETIME, TIME and TIMESTAMP columns with decimals specifier (e.g. TIMESTAMP(6) when using microseconds). Formerly, the fractional seconds part was simply omitted from the returned values.

  • Prepared statements now properly report the fractional seconds for DATETIME, TIME and TIMESTAMP columns with decimals specifier (e.g. TIMESTAMP(6) when using microseconds). Formerly, the fractional seconds part was simply omitted from the returned values. Please note that this only affects the usage of PDO_MYSQL with emulated prepares turned off (e.g. using the native preparation functionality). Statements using connections having PDO::ATTR_EMULATE_PREPARES=true (which is the default) were not affected by the bug fixed and have already been getting the proper fractional seconds values from the engine.

  • Reflection export to string now uses int and bool instead of integer and boolean, respectively.

  • If an SPL autoloader throws an exception, following autoloaders will not be executed. Previously all autoloaders were executed and exceptions were chained.

  • Mathematic operations involving SimpleXML objects will now treat the text as an int or float, whichever is more appropriate. Previously values were treated as ints unconditionally.

  • As of PHP 7.3.23, the names of incoming cookies are no longer url-decoded for security reasons.


  • 大小写不敏感的常量声明现已被废弃。将 true 作为第三个参数传递给 define() 将会导致一个废弃警告。大小写不敏感的使用(在读取时使用一个与声明时不同的大小写方式)也已被废弃。

  • 废弃:在一个命名空间中声明一个名为 assert() 的函数。 assert() 函数属于引擎特殊处理的情况,当在命名空间中使用相同名字去定义 函数时也许会导致不一致的行为。

  • 废弃:将一个非字符串内容传递给字符串搜索函数。 在将来所有待搜索的内容都将被视为字符串,而不是 ASCII 编码值。如果需要依赖这个特性,你应该 要么显示地进行类型转换(转为字符串),或者显示地调用 chr()。 以下是受到影响的方法:

  • fgetss() 函数和 string.strip_tags stream filter 已经被废弃。这同样影响了 SplFileObject::fgetss() 方法和 gzgetss() 函数。

  • 对于 FILTER_FLAG_SCHEME_REQUIRED 和 FILTER_FLAG_HOST_REQUIRED 常量的显示使用已被废弃。 总之,FILTER_VALIDATE_URL 已经隐含了这两者。

  • image2wbmp() 已被废弃。

  • 如果 PHP 关联的ICU ≥ 56, 那么 Normalizer::NONE 形式的使用将会导致抛出一个废弃警告。

  • 以下在文档中不存在的 mbereg_*() 别名已被废弃。请使用相应的 mb_ereg_*() 变体替代。

    • 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()
  • pdo_odbc.db2_instance_name ini 设置项在先前已被废弃。 它在文档中自 PHP 5.1.1 起被废弃

新特性

  • Heredoc 和 Nowdoc 语法变的更灵活。现在支持闭合标记符的缩进,并且不再强制闭合标记符的换行。

  • Array destructuring now supports reference assignments using the syntax [&$a, [$b, &$c]] = $d. The same is also supported for list().

  • instanceof now allows literals as the first operand, in which case the result is always false.

  • CompileError Exception instead of some Compilation Errors

  • Trailing commas in function and method calls are now allowed.

  • New options have been added to customize the FPM logging:

    • log_limit
    • log_buffering
    • decorate_workers_output
  • bcscale() can now also be used as getter to retrieve the current scale in use.

  • Full support for LDAP Controls has been added to the LDAP querying functions and ldap_parse_result()

  • Multibyte String Functions

    • Support for full case-mapping and case-folding has been added. Unlike simple case-mapping, full case-mapping may change the length of the string.

    • Case-insensitive string operations now use case-folding instead of case- mapping during comparisons. This means that more characters will be considered (case insensitively) equal now.

    • mb_convert_case() with MB_CASE_TITLE now performs title-case conversion based on the Cased and CaseIgnorable derived Unicode properties. In particular this also improves handling of quotes and apostrophes.

    • The Multibyte String data tables have been updated for Unicode 11.

    • The Multibyte String Functions now correctly support strings larger than 2GB.

    • Performance of the Multibyte String extension has been significantly improved across the board. The largest improvements are in case conversion functions.

    • The mb_ereg_* functions now support named captures.

  • Support for the completion_append_character and completion_suppress_append options has been added to readline_info(). These options are only available if PHP is linked against libreadline (rather than libedit).

阅读全文 »

目标及关键路径

  • 性能提升

从 PHP 7.1.x 移植到 PHP 7.2.x

这里可以找到原文

不向下兼容的变更

  • 防止 number_format() 返回负零,之前版本中,number_format() 有可能会返回 -0。虽然这是符合 IEEE 754 规范的,但是这样会导致可读性不好,新版本中会将这样的负数去掉。

  • 将数组转换为对象,或将对象转换为数组时,数字键现在得到了更好的处理(无论是通过显式转换还是通过 settype() 函数)。

  • get_class() 函数不再接受 null 参数,之前版本中,传递 nullget_class() 函数将返回当前类名。在新版本中,此行为会抛出一个 E_WARNING 错误。如果想实现与之前版本同样的效果,请不要传递任何参数进来。

  • 对非可数类型调用 count()(或 sizeof())函数,会抛出一个 E_WARNING 错误。

  • ext/hash 从资源变成对象

  • SSL/TLS 的下列默认选项被修改:

    • tls:// 默认为 TLSv1.0 or TLSv1.1 or TLSv1.2
    • ssl:// 成为 tls:// 的别名
    • STREAM_CRYPTO_METHOD_TLS_* 常量默认为 TLSv1.0 或 TLSv1.1 + TLSv1.2,替代之前的 TLSv1.0
  • 之前版本中,如果在一个闭包资源中使用 gettype() 会返回字符串 "unknown type",现在将会返回字符 "resource (closed)"

  • 之前版本中,对 __PHP_Incomplete_Class 调用 is_object() 函数会返回 false,现在会返回 true

  • 调用未定义的常量,现在会抛出一个 E_WARNING 错误(之前版本中为 E_NOTICE)。在下一个 PHP 大版本中,将会抛出一个 Error 错误。

  • 官方支持的最低 Windows 版本为 Windows 7/Server 2008 R2。

  • Compatibility checks upon default trait property values will no longer perform casting.

  • object 在之前的 PHP 7.0 版本 中被声明为软保留字(soft-reserved)。现在变更为强制保留字,禁止在任何类或接口中使用该名称。

  • NetWare 已不再被支持。

  • While array_unique() with SORT_STRING formerly copied the array and removed non-unique elements (without packing the array afterwards), now a new array is built by adding the unique elements. This can result in different numeric indexes.

  • The bcmod() function no longer truncates fractional numbers to integers. As such, its behavior now follows fmod(), rather than the % operator. For example bcmod('4', '3.5') now returns 0.5 instead of 1.

  • The hash_hmac(), hash_hmac_file(), hash_pbkdf2(), and hash_init() (with HASH_HMAC) functions no longer accept non-cryptographic hashes.

  • The json_decode() function option, JSON_OBJECT_AS_ARRAY, is now used if the second parameter (assoc) is null. Previously, JSON_OBJECT_AS_ARRAY was always ignored.

  • Sequences generated by rand() and mt_rand() for a specific seed may differ from PHP 7.1 on 64-bit machines (due to the fixing of a modulo bias bug in the implementation).

  • sql.safe_mode ini 设置项已被移除。

  • The zone element of the array returned by date_parse() and date_parse_from_format() represents seconds instead of minutes now, and its sign is inverted. For instance -120 is now 7200.

  • As of PHP 7.2.34, the names of incoming cookies are no longer url-decoded for security reasons.


  • 不带引号的字符串是不存在的全局常量,转化成他们自身的字符串。 在以前,该行为会产生 E_NOTICE,但现在会产生 E_WARNING。在下一个 PHP 主版本中,将抛出 Error 异常。

  • GD 扩展内的 png2wbmp()jpeg2wbmp() 现已被废弃,将在下一个 PHP 主版本中移除。

  • Intl 扩展废弃了 INTL_IDNA_VARIANT_2003 转化,为idn_to_ascii()idn_to_utf8() 的默认选项。 PHP 7.4 会把默认值设置为 INTL_IDNA_VARIANT_UTS46, 并在下一个 PHP 主版本中完全移除 INTL_IDNA_VARIANT_2003

  • __autoload() 方法已被废弃, 因为和 spl_autoload_register() 相比功能较差 (因为无法链式处理多个 autoloader), 而且也无法在两种 autoloading 样式中配合使用。

  • 当开启了 track_errors ini 设置,出现非致命错误时, 会在本地作用域创建 $php_errormsg 变量。 由于提供了更好的方式: error_get_last() 来获取此类错误信息,该功能被废弃。

  • 考虑到create_function() 函数的安全隐患问题(它是 eval() 的瘦包装器),该过时的函数现在已被废弃。 更好的选择是匿名函数

  • mbstring.func_overload ini 设置,由于此设置会影响环境中的字符串系列函数,带来相互操作中的问题,它现在已被废弃。

  • 转化任意表达式为(unset)类型,结果总是 null,所以这个多余的类型转化现在也就被废弃了。

  • 使用 parse_str() 时,不加第二个参数会导致查询字符串参数导入当前符号表。 考虑到安全隐患问题,不加第二个参数使用 parse_str() 的行为已被废弃。 此函数的第二个选项为必填项,它使查询字符串转为 Array。

  • 此函数基于未知的、取决于平台的 limb 尺寸产生随机数。因此,该函数已被废弃。 使用更好的方式产生随机数: GMP 扩展中的 gmp_random_bits()gmp_random_range()

  • 使用each() 函数遍历时,比普通的 foreach 更慢, 并且给新语法的变化带来实现问题。因此它被废弃了。

  • assert() 字符串参数将要求它能被 eval() 执行。 考虑到可能被执行远程代码,废弃了字符串的 assert(),最好提供 bool 的表达式。

  • $errcontext 参数包含了错误网站的所有本地变量。 考虑到它很少被用到,而且还会导致内部优化问题,它现在被废弃了。 代替用法:调试器应该自己取回错误站点的本地变量。

  • read_exif_data() 别名已被废弃 使用 exif_read_data() 函数代替。

新特性

  • 这种新的对象类型, object, 引进了可用于逆变(contravariant)参数输入和协变(covariant)返回任何对象类型。

  • 扩展文件不再需要通过文件加载 (Unix下以.so为文件扩展名,在Windows下以 .dll 为文件扩展名) 进行指定。可以在php.ini配置文件进行启用, 也可以使用 dl() 函数进行启用。

  • 当一个抽象类继承于另外一个抽象类的时候,继承后的抽象类可以重写被继承的抽象类的抽象方法。

  • 使用Argon2算法生成密码散列,Argon2 已经被加入到密码散列(password hashing) API (这些函数以 password_ 开头), 以下是暴露出来的常量:

    • PASSWORD_ARGON2I
    • PASSWORD_ARGON2_DEFAULT_MEMORY_COST
    • PASSWORD_ARGON2_DEFAULT_TIME_COST
    • PASSWORD_ARGON2_DEFAULT_THREADS
  • 新增 ext/PDO(PDO扩展) 字符串扩展类型,当你准备支持多语言字符集,PDO的字符串类型已经扩展支持国际化的字符集。以下是扩展的常量:

    • PDO::PARAM_STR_NATL
    • PDO::PARAM_STR_CHAR
    • PDO::ATTR_DEFAULT_STR_PARAM
  • 为 ext/PDO新增额外的模拟调试信息,PDOStatement::debugDumpParams()方法已经更新,当发送SQL到数据库的时候,在一致性、行查询(包括替换绑定占位符)将会显示调试信息。这一特性已经加入到模拟调试中(在模拟调试打开时可用)。

  • LDAP 扩展已经新增了EXOP支持. 扩展暴露以下函数和常量:

  • sockets扩展现在具有查找地址信息的能力,且可以连接到这个地址,或者进行绑定和解析。为此添加了以下一些函数:

  • 重写方法和接口实现的参数类型现在可以省略了。不过这仍然是符合LSP,因为现在这种参数类型是逆变的。

  • 命名空间可以在PHP 7中使用尾随逗号进行分组引入。

阅读全文 »

目标及关键路径

  • 提升性能
    • New SSA based optimization framework (embedded into opcache)
    • Global optimization of PHP bytecode based on type inference
    • Highly specialized VM opcode handlers

从 PHP 7.0.x 移植到 PHP 7.1.x

这里可以找到原文

不向后兼容的变更

  • 当传递参数过少时将抛出错误

  • Dynamic calls for certain functions have been forbidden (in the form of $func() or array_map('extract', ...), etc). These functions either inspect or modify another scope, and present with them ambiguous and unreliable behavior. The functions are as follows:

  • The following names cannot be used to name classes, interfaces, or traits:

  • Integer operations and conversions on numerical strings now respect scientific notation. This also includes the (int) cast operation, and the following functions: intval() (where the base is 10), settype(), decbin(), decoct(), and dechex().

  • mt_rand() will now default to using the fixed version of the Mersenne Twister algorithm. If deterministic output from mt_srand() was relied upon, then the MT_RAND_PHP with the ability to preserve the old (incorrect) implementation via an additional optional second parameter to mt_srand().

  • rand() and srand() have now been made aliases to mt_rand() and mt_srand(), respectively. This means that the output for the following functions have changed: rand(), shuffle(), str_shuffle(), and array_rand().

  • The ASCII delete control character (0x7F) can no longer be used in identifiers that are not quoted.

  • If the error_log ini setting is set to syslog, the PHP error levels are mapped to the syslog error levels. This brings finer differentiation in the error logs in contrary to the previous approach where all the errors are logged with the notice level only.

  • 对于在执行构造方法时抛出异常的对象,现在析构方法绝不会被调用。在先前的版本中,这个行为取决于对象是否在构造方法以外的地方呗引用(例如一个错误堆栈回溯)

  • call_user_func()不再支持对传址的函数的调用

  • 对字符串使用一个空索引操作符(例如$str[] = $x)将会抛出一个致命错误, 而不是静默地将其转为一个数组。

  • 下列ini配置项已经被移除:

    • session.entropy_file
    • session.entropy_length
    • session.hash_function
    • session.hash_bits_per_character
  • The order of the elements in an array has changed when those elements have been automatically created by referencing them in a by reference assignment.

  • The internal sorting algorithm has been improved, what may result in different sort order of elements, which compare as equal, than before.

  • The error message for E_RECOVERABLE errors has been changed from “Catchable fatal error” to “Recoverable fatal error”.

  • DateTime and DateTimeImmutable now properly incorporate microseconds when constructed from the current time, either explicitly or with a relative string (e.g. "first day of next month"). This means that naive comparisons of two newly created instances will now more likely return false instead of true:

  • Fatal errors to Error exceptions conversions

  • Variables bound to a closure via the use construct cannot use the same name as any superglobals, $this, or any parameter.

  • long2ip() now expects an int instead of a string.

  • JSON encoding and decoding

    • The serialize_precision ini setting now controls the serialization precision when encoding doubles.

    • Decoding an empty key now results in an empty property name, rather than empty as a property name.

  • Drop support for the sslv2 stream

  • Return statements without argument in functions which declare a return type now trigger E_COMPILE_ERROR (unless the return type is declared as void), even if the return statement would never be reached.


  • mcrypt 扩展已经过时了大约10年,并且用起来很复杂。因此它被废弃并且被 OpenSSL 所取代。 从PHP 7.2起它将被从核心代码中移除并且移到PECL中。

  • 对于mb_ereg_replace()mb_eregi_replace()e模式修饰符现在已被废弃。

新特性

  • 参数以及返回值的类型现在可以通过在类型前加上一个问号使之允许为空。 当启用这个特性时,传入的参数或者函数返回的结果要么是给定的类型,要么是 null 。

  • 一个新的返回值类型void被引入。 返回值声明为 void 类型的方法要么干脆省去 return 语句,要么使用一个空的 return 语句。 对于 void 函数来说,null 不是一个合法的返回值。

  • 短数组语法([])现在作为list()语法的一个备选项,可以用于将数组的值赋给一些变量(包括在foreach中)。

  • 现在起支持设置类常量的可见性。

  • 现在引入了一个新的被称为iterable的伪类 (与callable类似)。 这可以被用在参数或者返回值类型中,它代表接受数组或者实现了Traversable接口的对象。 至于子类,当用作参数时,子类可以收紧父类的iterable类型到array 或一个实现了Traversable的对象。对于返回值,子类可以拓宽父类的 array或对象返回值类型到iterable

  • 一个catch语句块现在可以通过管道字符(|)来实现多个异常的捕获。 这对于需要同时处理来自不同类的不同异常时很有用。

  • 现在list()和它的新的[]语法支持在它内部去指定键名。这意味着它可以将任意类型的数组 都赋值给一些变量(与短数组语法类似)

  • 现在所有支持偏移量的字符串操作函数 都支持接受负数作为偏移量,包括通过[]{}操作字符串下标。在这种情况下,一个负数的偏移量会被理解为一个从字符串结尾开始的偏移量。

  • 通过给openssl_encrypt()openssl_decrypt() 添加额外参数,现在支持了AEAD (模式 GCM and CCM)。

  • Closure新增了一个静态方法,用于将callable快速地 转为一个Closure 对象。

  • 一个新的名为 pcntl_async_signals() 的方法现在被引入, 用于启用无需 ticks (这会带来很多额外的开销)的异步信号处理。

  • 对服务器推送的支持现在已经被加入到 CURL 扩展中( 需要版本 7.46 或更高)。这个可以通过 curl_multi_setopt() 函数与新的常量 CURLMOPT_PUSHFUNCTION 来进行调节。常量 CURL_PUST_OKCURL_PUSH_DENY 也已经被添加进来,以便服务器推送的回调函数来表明自己会同意或拒绝处理。

  • 新增 tcp_nodelay 选项。

阅读全文 »

目标及关键路径

  • 提升性能,预期提升30%+,实际提升了100%+
    • 降低内存占用, 提高缓存友好性, 降低执行的指令数
      • 优化ZVAL

        • ZVAL这个结构体的大小是(在64位系统)24个字节,在zval.value联合体中, zend_object_value是最大的长板, 它导致整个value需要16个字节

          • 优化结构,在64位环境下,现在只需要16个字节
        • PHP中大量的结构体都是基于Hashtable实现的, 增删改查Hashtable的操作占据了大量的CPU时间, 而字符串要查找首先要求它的Hash值

          • 把一个字符串的Hash值计算好以后, 就存下来, 避免再次计算
        • PHP的zval大部分都是按值传递, 写时拷贝的值, 但是有俩个例外, 就是对象和资源, 他们永远都是按引用传递, 这样就造成一个问题, 对象和资源在除了zval中的引用计数以外, 还需要一个全局的引用计数, 这样才能保证内存可以回收. 所以在PHP5的时代, 以对象为例, 它有俩套引用计数, 一个是zval中的, 另外一个是obj自身的计数。在获取object时,经过漫长的多次内存读取, 才能获取到真正的objec对象本身,效率低

          • 对于在zval的value字段中能保存下的值, 就不再对他们进行引用计数了, 而是在拷贝的时候直接赋值, 这样就省掉了大量的引用计数相关的操作
          • 标志位,方便判断是否需要进行引用计数
          • PHP7中在取一个对象的类的时候,就会非常方便了, 直接zvalu.value.obj->ce即可,一些类所自定的handler也就可以很便捷的访问到了
        • 因为引用计数是作用在zval的, 那么就会导致如果要拷贝一个字符串类型的zval, 我们别无他法只能复制这个字符串

          • 用value来保存一个指针, 这个指针指向这个具体的值, 引用计数也随之作用于这个值上, 而不在是作用于zval上了.
        • PHP5的时代, 采用的是写时分离,同一个变量,只要曾经被引用过,再被赋值,就会触发变量复制(分离),拖慢性能

        • zval在PHP5的时代,也常作为临时变量来高频使用,并在使用过程中也会在堆内存分配给它

          • zval预先分配,移除了MAKE_STD_ZVAL/ALLOC_ZVAL宏, 不再支持存堆内存上申请zval. 函数内部使用的zval要么来自外面输入, 要么使用在栈上分配的临时zval
      • 优化HashTable

        • Hashtable在PHP中,应用最多的是保存各种zval, 而PHP5的HashTable设计的太通用
          • 可以设计为专门为了存储zval而优化, 从而能减少内存占用。
          • 通过基于位操作来设计存储方案,节省内存
        • 缓存局部性问题, 因为PHP5的Hashtable的Bucket,包括zval都是独立分配的,并且采用了List来串Hashtable中的所有元素,会导致在遍历或者顺序访问一个数组的时候,缓存不友好。
          • 数据独立保存到一个连续数组,遍历时就可以顺序访问一块连续的内存,zval直接保存到数组元素中,在绝大部分情况下(不需要外部指针的内容,比如long,bool之类的)就可以不需要任何额外的zval指针解引用了,缓存局部性友好
      • 优化OBJECT

        • 在PHP5中,只有resource和object是引用传递,也就是说在赋值,传递的时候都是传递的本身,也正因为如此,Object和Resource除了使用了Zval的引用计数以外,还采用了一套独立自身的计数系统
          • zval中直接保存了zend_object对象的指针,统一并简化引用计数方案
      • 编译优化

        • GCC PGO,尝试分析PGO都做了些什么优化, 然后把一些通用的优化手工Apply到PHP7中
        • 可通过产品场景训练GCC
      • 缓存优化

        • 默认的内存是以4KB分页的,而虚拟地址和内存地址是需要转换的, 而这个转换是要查表的,CPU为了加速这个查表过程都会内建TLB(Translation Lookaside Buffer), 显而易见如果虚拟页越小,表里的条目数也就越多,而TLB大小是有限的,条目数越多TLB的Cache Miss也就会越高
      • 让PHP7达到最高性能的几个Tips

从 PHP 5.6.x 移植到 PHP 7.0.x

更多细节可以阅读这里

不向后兼容的变更

  • set_exception_handler() 不再保证收到的一定是 Exception 对象

  • 当内部构造器失败的时候,总是抛出异常

  • 解析错误会抛出 ParseError 异常。 对于 eval() 函数,需要将其包含到一个 catch 代码块中来处理解析错误。

  • 原有的 E_STRICT 警告都被迁移到其他级别。 E_STRICT 常量会被保留,所以调用 error_reporting(E_ALL|E_STRICT) 不会引发错误。

  • 对变量、属性和方法的间接调用现在将严格遵循从左到右的顺序来解析,而不是之前的混杂着几个特殊案例的情况。

  • 关于list()处理方式的变更

    • list() 现在会按照变量定义的顺序来给他们进行赋值,而非反过来的顺序。 通常来说,这只会影响list() 与数组的[]操作符一起使用的案例

    • list() 结构现在不再能是空的。

    • list() 不再能解开字符串(string)变量。 你可以使用str_split()来代替它。

  • 在 PHP 5中,在以引用方式传递函数参数时,使用冗余的括号对可以隐匿严格标准 的警告。现在,这个警告总会触发。

  • foreach发生了细微的变化,控制结构, 主要围绕阵列的内部数组指针和迭代处理的修改。

    • 在PHP7之前,当数组通过 foreach 迭代时,数组指针会移动。现在开始,不再如此

    • 当默认使用通过值遍历数组时,foreach 实际操作的是数组的迭代副本,而非数组本身。这就意味着,foreach 中的操作不会修改原数组的值。

    • 当使用引用遍历数组时,现在 foreach 在迭代中能更好的跟踪变化。

    • 迭代一个非Traversable对象将会与迭代一个引用数组的行为相同。 这将导致在对象添加或删除属性时,foreach通过引用遍历时,有更好的迭代特性也能被应用

  • Changes to integer handling

    • 在之前,一个八进制字符如果含有无效数字,该无效数字将被静默删节(0128 将被解析为 012). 现在这样的八进制字符将产生解析错误。

    • 以负数形式进行的位移运算将会抛出一个 ArithmeticError

    • 超出 integer 位宽的位移操作(无论哪个方向)将始终得到 0 作为结果。在从前,这一操作是结构依赖的。

    • 之前的版本中,当 0 被做为除数时,无论是除数 (/) 或取模 (%) 操作,都会抛出一个 E_WARNING 错误并返回 false。现在,除法运算符 (/) 会返回一个由 IEEE 754 指定的浮点数:+INF, -INF 或 NAN。取模操作符 (%) 则会抛出一个 DivisionByZeroError 异常,并且不再产生 E_WARNING 错误。

  • string处理上的调整

    • 十六进制字符串不再被认为是数字

    • 由于新的 Unicode codepoint escape syntax语法, 紧连着无效序列并包含\u{ 的字串可能引起致命错误。 为了避免这一报错,应该避免反斜杠开头。

  • 被移除的函数(Removed functions)

    • 这两个函数从PHP 4.1.0 开始被废弃,应该使用 call_user_func()call_user_func_array()。 你也可以考虑使用 变量函数 或者 ... 操作符。

    • 所有 ereg 系列函数被删掉了。 PCRE 作为推荐的替代品。

    • 已废弃的 mcrypt_generic_end() 函数已被移除,请使用mcrypt_generic_deinit()代替。

    • 已废弃的 mcrypt_ecb(), mcrypt_cbc(), mcrypt_cfb()mcrypt_ofb() 函数已被移除,请配合恰当的**MCRYPT_MODE_*** 常量来使用 mcrypt_decrypt()进行代替。

    • 所有 ext/mysql 函数已被删掉了。 如何选择不同的 MySQL API,详情请见 选择 MySQL API

    • 所有 ext/mssql 函数已被移除。

    • 已废弃的 datefmt_set_timezone_id()IntlDateFormatter::setTimeZoneID() 函数已被移除,请使用 datefmt_set_timezone()IntlDateFormatter::setTimeZone()代替。

    • 移除了 set_magic_quotes_runtime() 和它的别名 magic_quotes_runtime()。 它们在 PHP 5.3.0 中已经被废弃, 并由于 PHP 5.4.0 移除魔术引号(Magic Quotes)而没有用处。

    • 已废弃的 set_socket_blocking() 函数已被移除,请使用stream_set_blocking()代替。

    • dl()在 PHP-FPM 不再可用,在 CLI 和 embed SAPIs 中仍可用。

    • 以下GD Type1函数被删除, 推荐使用 TrueType 字体和相关的函数作为替代。

      • imagepsbbox()
      • imagepsencodefont()
      • imagepsextendfont()
      • imagepsfreefont()
      • imagepsloadfont()
      • imagepsslantfont()
      • imagepstext()
  • 被移除掉的 INI 配置指令

    • always_populate_raw_post_data
    • asp_tags
    • xsl.security_prefs 指令被移除 在预处理的时候,取而代之的方法 XsltProcessor::setSecurityPrefs() 应该被调用到
  • new 操作符创建的对象不能以引用方式赋值给变量

  • 不能以下列名字来命名类、接口以及 trait:

    • bool
    • int
    • float
    • string
    • null
    • true
    • false
  • 不建议以下列名字来命名类、接口以及 trait,在以后的迭代中,会作为保留关键字:

    • resource
    • object
    • mixed
    • numeric
  • 使用类似 ASP 的标签,以及 script 标签来区分 PHP 代码的方式被移除。

  • 在不匹配的上下文中以静态方式调用非静态方法, 在 PHP 5.6 中已经废弃, 但是在 PHP 7.0 中, 会导致被调用方法中未定义 $this 变量,以及此行为已经废弃的警告。

  • 在使用 yield 关键字的时候,不再需要括号, 并且它变更为右联接操作符,其运算符优先级介于 print=> 之间。 可以通过使用括号来消除歧义。

  • 函数定义不可以包含多个同名参数

  • Switch 语句不可以包含多个 default 块

  • 当在函数代码中使用 func_get_arg()func_get_args() 函数来检视参数值, 或者使用 debug_backtrace() 函数查看回溯跟踪, 以及在异常回溯中所报告的参数值是指参数当前的值(有可能是已经被函数内的代码改变过的值), 而不再是参数被传入函数时候的原始值了。

  • 不再提供 $HTTP_RAW_POST_DATA 变量。 请使用 php://input 作为替代。

  • 在 INI 文件中,不再支持以 # 开始的注释行, 请使用 ;(分号)来表示注释。

  • JSON 扩展已经被 JSOND 扩展取代。 对于数值的处理,有以下两点需要注意的: 第一,数值不能以点号(.)结束 (例如,数值 34. 必须写作 34.0 或 34)。 第二,如果使用科学计数法表示数值,e 前面必须不是点号(.) (例如,3.e3 必须写作 3.0e3 或 3e3)。 另外,空字符串不再被视作有效的 JSON 字符串。

  • 在数值溢出的时候,内部函数将会失败,将浮点数转换为整数的时候,如果浮点数值太大,导致无法以整数表达的情况下, 在之前的版本中,内部函数会直接将整数截断,并不会引发错误。 在 PHP 7.0 中,如果发生这种情况,会引发 E_WARNING 错误,并且返回 null。

  • 在自定义会话处理器中,如果函数的返回值不是 false,也不是 -1, 会引发致命错误。现在,如果这些函数的返回值不是布尔值,也不是 -1 或者 0,函数调用结果将被视为失败,并且引发 E_WARNING 错误。

  • 由于内部排序算法进行了提升, 可能会导致对比时被视为相等的多个元素之间的顺序不稳定。

  • 在循环或者 switch 语句之外使用 break 和 continue 被视为编译型错误(之前视为运行时错误),会引发 E_COMPILE_ERROR 错误。

  • Mhash 扩展已经被完全整合进 Hash 扩展了。 因此,不要再使用 extension_loaded() 函数来检测是否支持 MHash 扩展了, 建议使用 function_exists() 函数来进行检测。 另外,函数 get_loaded_extensions() 以及相关的特性中,也不再报告 和 MHash 扩展相关的信息了。

  • declare(ticks) 指示符不再泄漏到不同的编译单元中。


  • PHP4 风格的构造函数(方法名和类名一样)将被弃用,并在将来移除。 如果在类中仅使用了 PHP4 风格的构造函数,PHP7 会产生 E_DEPRECATED 警告。 如果还定义了 __construct() 方法则不受影响。

  • 废弃了 静态(Static) 调用未声明成 static 的方法,未来可能会彻底移除该功能。

  • 废弃了 password_hash() 函数中的盐值选项,阻止开发者生成自己的盐值(通常更不安全)。 开发者不传该值时,该函数自己会生成密码学安全的盐值。因此再无必要传入自己自定义的盐值。

  • 废弃了 capture_session_meta 内的 SSL 上下文选项。 现在可以通过 stream_get_meta_data() 获取 SSL 元数据(metadata)。

  • LDAP相关的以下函数已被废弃:

    • ldap_sort()
  • 移除的扩展

    • ereg
    • mssql
    • mysql
    • sybase_ct
  • 移除的 SAPI

    • aolserver
    • apache
    • apache_hooks
    • apache2filter
    • caudium
    • continuity
    • isapi
    • milter
    • nsapi
    • phttpd
    • pi3web
    • roxen
    • thttpd
    • tux
    • webjames

新特性

  • 标量类型声明

  • 返回值类型声明

  • 由于日常使用中存在大量同时使用三元表达式和 isset()的情况, 我们添加了null合并运算符 (??) 这个语法糖。如果变量存在且值不为null, 它就会返回自身的值,否则返回它的第二个操作数。

  • 太空船操作符用于比较两个表达式。当$a小于、等于或大于$b时它分别返回-1、0或1。 比较的原则是沿用 PHP 的常规比较规则进行的。

  • 通过 define() 定义常量数组

  • 现在支持通过new class 来实例化一个匿名类,这可以用来替代一些“用后即焚”的完整类定义。

  • 这接受一个以16进制形式的 Unicode codepoint,并打印出一个双引号或heredoc包围的 UTF-8 编码格式的字符串。 可以接受任何有效的 codepoint,并且开头的 0 是可以省略的。

  • Closure::call() 现在有着更好的性能,简短干练的暂时绑定一个方法到对象上闭包并调用它。

  • 为unserialize()提供过滤,这个特性旨在提供更安全的方式解包不可靠的数据。它通过白名单的方式来防止潜在的代码注入。

  • 新增加的 IntlChar 类旨在暴露出更多的 ICU 功能。这个类自身定义了许多静态方法用于操作多字符集的 unicode 字符。

  • 预期是向后兼用并增强之前的 assert() 的方法。 它使得在生产环境中启用断言为零成本,并且提供当断言失败时抛出特定异常的能力。

  • 从同一 namespace 导入的类、函数和常量现在可以通过单个 use 语句 一次性导入了。

  • 生成器可以返回表达式,此特性基于 PHP 5.5 版本中引入的生成器特性构建的。 它允许在生成器函数中通过使用 return 语法来返回一个表达式 (但是不允许返回引用值), 可以通过调用 Generator::getReturn() 方法来获取生成器的返回值, 但是这个方法只能在生成器完成产生工作以后调用一次。

  • 现在,只需在最外层生成其中使用 yield from, 就可以把一个生成器自动委派给其他的生成器, Traversable 对象或者 array。

  • 新加的函数 intdiv() 用来进行 整数的除法运算。

  • session_start() 可以接受一个 array 作为参数, 用来覆盖 php.ini 文件中设置的 会话配置选项

  • 在 PHP 7 之前,当使用 preg_replace_callback() 函数的时候, 由于针对每个正则表达式都要执行回调函数,可能导致过多的分支代码。 而使用新加的 preg_replace_callback_array() 函数, 可以使得代码更加简洁。

  • 新加入两个跨平台的函数: random_bytes()random_int() 用来产生高安全级别的随机字符串和随机整数。

  • 可以使用 list() 函数来展开实现了 ArrayAccess 接口的对象

  • 允许在克隆表达式上访问对象成员,例如: (clone $foo)->bar()。

阅读全文 »

有什么变化

它的核心是 Zend 引擎 2 代,引入了新的对象模型和大量新功能。

http://people.apache.org/~jim/ApacheCons/ApacheCon2002/pdf/suraski-php-02.pdf

新增了什么

  • New php.ini options:

    • “session.hash_function” and “session.hash_bits_per_character”. (Sascha)
    • “mail.force_extra_paramaters”. (Derick)
    • “register_long_arrays”. (Zeev)
  • Added new iconv functions. (Moriyoshi)

    • iconv_strlen()
    • iconv_substr()
    • iconv_strpos()
    • iconv_strrpos()
    • iconv_mime_decode()
    • iconv_mime_encode()
  • Added misc. new functions:

    • ldap_sasl_bind(). ([email protected], Jani)
    • imap_getacl(). (Dan, Holger Burbach)
    • file_put_contents(). (Sterling)
    • proc_nice() - Changes priority of the current process. (Ilia)
    • pcntl_getpriority() and pcntl_setpriority(). (Ilia)
    • idate(), date_sunrise() and date_sunset(). (Moshe Doron)
    • strpbrk() - Searches a string for a list of characters. (Ilia)
    • get_headers() - Returns headers sent by the server of the specified URL. (Ilia)
    • str_split() - Breaks down a string into an array of elements based on length. (Ilia)
    • array_walk_recursive(). (Ilia)
    • array_combine(). (Andrey)
  • Added optional parameter to get_browser() to make it return an array. (Jay)

  • Added optional parameter to openssl_sign() to specify the hashing algorithm.([email protected], Derick)

  • Added optional parameter to sha1(), sha1_file(), md5() and md5_file() which makes them return the digest as binary data. (Michael Bretterklieber, Derick)

  • Added optional parameter to mkdir() to make directory creation recursive. (Ilia)

  • Added optional parameter to file() which makes the result array not contain the line endings and to skip empty lines. (Ilia)

  • Added new range() functionality:

    • Support for float modifier. (Ilia)
    • Detection of numeric values inside strings passed as high & low. (Ilia)
    • Proper handle the situations where high == low. (Ilia)
    • Added an optional step parameter. (Jon)
  • Added encoding detection feature for expat XML parser. (Adam Dickmeiss, Moriyoshi)

  • Added missing multibyte (unicode) support and numeric entity support to html_entity_decode(). (Moriyoshi)

  • Added IPv6 support to ext/sockets. (Sara)

  • Added input filter support. See README.input_filter for more info. (Rasmus)

  • Added a replace count for str_[i]replace(), see #8218. (Sara)

移除了什么

  • Removed the bundled MySQL client library. (Sterling)

修改了什么

  • Switch to using Zend Engine 2, which includes numerous engine level improvements. A full overview may be downloaded from http://www.zend.com/engine2/ZendEngine-2.0.pdf (PDF).

  • The SQLite (http://www.hwaci.com/sw/sqlite/) extension is now bundled and enabled by default. (Wez, Marcus, Tal)

  • Improved the speed of internal functions that use callbacks by 40% due to a new internal fast_call_user_function() function. (Sterling)

  • Completely Overhauled XML support (Rob, Sterling, Chregu, Marcus)

    • Brand new Simplexml extension
    • New DOM extension
    • New XSL extension
    • Moved the old DOM-XML and XSLT extensions to PECL
    • ext/xml can now use both libxml2 and expat to parse XML
    • Removed bundled expat
  • Improved the streams support: (Wez, Sara, Ilia)

    • Improved performance of readfile(), fpassthru() and some internal streams operations under Win32.
    • stream_socket_client() - similar to fsockopen(), but more powerful.
    • stream_socket_server() - Creates a server socket.
    • stream_socket_accept() - Accept a client connection.
    • stream_socket_get_name() - Get local or remote name of socket.
    • stream_copy_to_stream()
    • stream_get_line() - Reads either the specified number of bytes or until the ending string is found.
    • Added context property to userspace streams object.
    • Added generic crypto interface for streams (supports dynamic loading of OpenSSL)
    • Added lightweight streaming input abstraction to the Zend Engine scanners to provide uniform support for include()'ing data from PHP streams across all platforms.
    • Added ‘string.base64’ stream filter.
    • Renamed stream_register_wrapper() to stream_wrapper_register().
    • Added “ftp://” wrapper support to opendir(), stat() and unlink().
    • Added context options ‘method’, ‘header’ and ‘content’ for “http://” fopen wrapper.
  • Improved the GD extension: (Pierre-Alain Joye, Ilia)

    • imagefilter() - Apply different filters to image. (Only available with bundled GD library)
    • Antialiased drawing support:
      • imageantialias() - (de)active antialias
      • imageline() and imagepolygon() antialias support
  • Changed the length parameter in fgetss() to be optional. (Moriyoshi)

  • Changed ini parser to allow for handling of quoted multi-line values. (Ilia)

  • Changed get_extension_funcs() to return list of the built-in Zend Engine functions if “zend” is specified as the module name. (Ilia)

  • Changed array_search() to accept also objects as a needle. (Moriyoshi)

  • Changed ext/mcrypt to require libmcrypt version 2.5.6 or greater. (Derick)

  • Changed uniqid() parameters to be optional and allow any prefix length. (Marcus)

修复了什么BUG

阅读全文 »

有什么变化

新增了什么

  • Added Win32 build files for Informix driver and make it compile with ZTS (danny)

  • Added tmpfile() function (Stig)

  • min(),max(),a[r]sort(),[r]sort(),k[r]sort() now work consistent with the language-core. (Thies)

  • tempnam() now uses mkstemp() if available (Stig)

  • serialize() and var_dump() now honor the precision as set in php.ini for doubles. (Thies)

  • Added Microsoft SQL Server module for Win32 (Frank)

  • Added support for forcing a variable number of internal function arguments by reference. (Andi & Zeev, Zend Engine)

  • Implemented getprotoby{name,number} (Evan)

  • Added array_pad() function. (Andrei)

  • Added new getservby{name,port} functions. (Evan)

  • Added session.cookie_path and session.cookie_domain (Sascha)

  • Continue processing PHP_INI_SYSTEM knownDirectives after extension= (Sam Ruby)

  • Enable IBM DB2 support - Tested against DB2 6.1 UDB on Linux (Rasmus)

  • Added new str_repeat() function. (Andrei)

  • implemented OCI8 $lob->WriteToFile() function - very useful for streaming large amounts of LOB-Data without to need of a huge buffer. (Thies)

  • Added session.use_cookies option (Sascha)

  • Added getcwd() function. (Thies)

  • added === operator support. (Andi & Thies, Zend Engine)

  • Added is_resource(), is_bool() functions. (Thies)

  • Thies introduced ZEND_FETCH_RESOURCE2 (Danny).

  • Added Informix driver to list of maintained extensions. (Danny).

  • IXF_LIBDIR environment variable specifies alternate Informix library path for configure (Danny).

  • You can use resources as array-indices again (Thies, Zend Engine)

  • fdf support ported; not completely tested with latest version 4.0 for glibc (Uwe)

  • OCI8 connections are now kept open as long as they are referenced (Thies)

  • Ported range() and shuffle() from PHP 3 to PHP 4 (Andrei)

  • Added the ability to use variable references in the array() construct. For example, array(“foo” => &$foo). (Andi, Zend Engine)

  • Added array_reverse() function (Andrei)

  • Generalized server-API build procedure on UNIX (Stig)

  • Added ‘–disable-rpath’ option (Sascha)

  • Added AOLserver SAPI module (Sascha)

  • Added support for the Easysoft ODBC-ODCB Bridge ([email protected])

  • Added extra metadata functions to ODBC, SQLTables etc ([email protected])

  • Implemented object serialization/deserialization in WDDX (Andrei)

  • Added krsort() function (Thies)

  • Added func_num_args(), func_get_arg() and func_get_args() for standard access to variable number of arguments functions (Zeev)

  • Added FTP support (Andrew Skalski)

  • Added optional allowable_tags arguments to strip_tags(), gzgetss() and fgetss() to allow you to specify a string of tags that are not to be stripped (Rasmus)

  • Added array_count_values() function. (Thies)

  • snmp, pgsql, mysql and gd modules can be built as dynamically loaded modules (Greg)

  • Added user-level callbacks for session module (Sascha)

  • Added support for unknown POST content types (Zeev)

  • Added “wddx” serialization handler for session module (Sascha) (automatically enabled, if you compile with --with-wddx)

  • PHP 4.0 now serializes Objects as ‘O’ (not understood by PHP 3.0), but unserializes PHP 3.0 serialized objects as expected. (Thies)

  • Made serialize/unserialize work on classes. If the class is known at unserialize() time, you’ll get back a fully working object! (Thies)

  • Made it possible to specify external location of PCRE library (Andrei)

  • OCI8 supports appending and positioning when saving LOBs (Thies)

  • Added metaphone support (Thies)

  • OCI8 Driver now supports LOBs like PHP 3.0. (Thies)

  • var_dump now dumps the properties of an object (Thies)

  • Added support for transparent session id propagation (Sascha)

  • Made WDDX serialize object properties properly (Andrei)

  • Added session_unset() function (Andrei)

  • Added gpc_globals variable directive to php.ini. By default it is On, but if it is set to Off, GET, POST and Cookie variables will not be inserted to the global scope. Mostly makes sense when coupled with track_vars (Zeev)

  • Added versioning support for shared library (Sascha) This allows concurrent use of PHP 3.0 and PHP 4.0 as Apache modules. See the end of the INSTALL file for more information.

  • Added second parameter to array_keys which specifies search value for which the key should be returned (Andrei)

  • Make set_time_limit() work on Unix (Rasmus)

  • Added connection handling support (Rasmus)

  • Added shared memory module for session data storage (Sascha)

  • Ported newest GetImageSize (Thies)

  • Added session compile support in Win32 (Andi)

  • Added -d switch to the CGI binary that allows overriding php.ini values from the command line (Zeev)

  • Added output_buffering directive to php.ini, to enable output buffering for all PHP scripts - default is off (Zeev).

  • Added session.extern_referer_chk which checks whether session ids were referred to by an external site and eliminates them (Sascha)

  • Introduced general combined linear congruential generator (Sascha)

  • Made ldap_close back into an alias for ldap_unbind (Andrei)

移除了什么

  • Cleaned up File-Module (Thies)
  • Cleaned up Directory-Module (Thies)

修改了什么

  • ucfirst()/ucwords() no longer modify arg1 (Thies)

  • Upgraded regex library to alpha3.8 (Sascha)

  • Output-Buffering system is now Thread-Safe. (Thies)

  • XML_Parse_Into_Struct no longer eats data. (Thies)

  • unserialize() now gives a notice when passed invalid data. (Thies)

  • Improved the Win32 COM module to support [out] parameters (Boris Wedl)

  • setlocale doesn’t anymore screw up things if you forgot to change it back to the original settings. (Jouni)

  • Switched to new system where ChangeLog is automagically updated from commit messages. NEWS file is now the place for public announcements. (Andrei)

  • Improved UNIX build system. Now utilizes libtool (Sascha)

  • Updated Zend garbage collection with a much more thorough method. (Andi, Zend Engine)

  • Some more XML fixes/cleanups (Thies)

  • Updated preg_replace() so that if any argument passed in is an array it will make a copy of each entry before converting it to string so that the original is intact. If the subject is an array then it will preserve the keys in the output as well (Andrei)

  • Configure speedup (Stig)

  • Upgrade some more internal functions to use new Zend function API. (Thies, Zend Engine)

  • Informix driver : Changed ifx.ec to use the new high-performance ZEND API. (Danny)

  • Upgraded math-funtions to use new Zend function API (Thies)

  • Upgraded a lot internal functions to use new Zend function API (Thies)

  • Updated OCI8 to use the new high-performance Zend function API. (Thies)

  • Updated ODBC to use the new high-performance Zend function API (kara)

  • Updated zlib to use the new high-performance Zend function API. (Stefan)

  • Updated preg_split() to allow returning only non-empty pieces (Andrei)

  • Updated PCRE to use the new high-performance Zend function API (Andrei)
    8 Updated session, dba, mhash, mcrypt, sysvshm, sysvsem, gettext modules to use the new high-performance Zend function API (Sascha)

  • Updated WDDX to use the new high-performance Zend function API (Andrei)

  • Updated XML to use the new high-performance Zend function API. (Thies)

  • Updated Oracle to use the new high-performance Zend function API. (Thies)

  • Improved the performance of the MySQL module significantly by using the new high-performance Zend function API. (Zeev)

  • Extended var_dump to handle resource type somewhat (Andrei)

  • Resourcified Oracle (Thies)

  • Upgraded var_dump() to take multiple arguments (Andrei)

  • Reworked preg_* functions according to the new PCRE API, which also made them behave much more like Perl ones (Andrei)

  • Updated bundled PCRE library to version 2.08 (Andrei)

  • count()/is_array/is_object… speedups. (Thies)

  • OCI8 doesn’t use define callbacks any longer. (Thies)

  • Rewrote the GET/POST/Cookie data reader to support multi-dimensional arrays! (Zeev)

  • Renamed allow_builtin_links to expose_php (defaults to On). This directive tells PHP whether it may expose its existence to the outside world, e.g. by adding itself to the Web server header (Zeev)

  • Resourcified Informix driver (Danny)

  • New resource handling for odbc, renamed to php_odbc.[ch]

  • Improved the Sybase-CT module to make use of resources (Zeev)

  • Improved the mSQL module to make use of resources (Zeev)

  • Changed mysql_query() and mysql_db_query() to return false in case of saving the result set data fails (Zeev)

  • Improved the resource mechanism - resources were not getting freed as soon as they could (Zeev)

  • Improved session id generation (Sascha)

  • Improved speed of uniqid() by using the combined LCG and removing the extra usleep() (Sascha)

  • OciFetchInto now resets the returned array in all cases (Thies)

  • Oracle is now ZTS-Safe (Thies)

  • OCI8 is now ZTS-Safe (Thies)

  • Imported PHP 3.0 diskfreespace() function (Thies)

修复了什么BUG

  • Fixed strtr() not to modify arg1 (Thies)

  • Fixed selecting nested-tables in OCI8. (Thies)

  • RFC-854 fix for internal FTP-Code. Commands have to end in “\r\n” (Thies)

  • Fixed OpenLink ODBC support (Stig)

  • Fixed garbage returned at the end of certain Sybase-Columns (Thies) Patch submitted by: [email protected]

  • Fixed parse_url(‘-’) crash. (Thies)

  • Fixed shuffle() so that it no longer breaks on Solaris. (Andrei)

  • Fixed zombie problem in shell_exec() and $a = `some_command` constructs. (Thies)

  • Fixed gmmktime() so that the following should always be true: gmmktime([args]) == mktime([args]) + date(‘Z’, mktime([args])) (Jouni)

  • Fixed refcount problem in XML module. (Thies)

  • Fixed crash in HTTP_RAW_POST_DATA handling (Thies)

  • Fixed pg_fetch_array() with three arguments (Sascha) Patch submitted by: [email protected]

  • Small fix in Ora_Close (Thies)

  • Fixed header(“HTTP/…”); behaviour (Sascha)

  • Fixed backwards incompatibility with ereg() (Thies)

  • Fixed LOB/Persistent-Connection related OCI8-Crash (Thies)

  • Fixed XML Callbacks. (Thies)

  • Fixed bug in odbc_setoption, getParameter call incorrect ([email protected])

  • Fixed NULL-Column problem in Oracle-Driver (Thies)

  • Fixed SEGV in mcal make_event_object() and typo in mcal_list_alarms() (Andrew Skalski)

  • Fixed Ora_PLogon (Thies)

  • Fixed a memory leak in the Apache per-directory directives handler (Zeev)

  • OCI8 fix for fetching empty LOBs (Thies)

  • Fixed unserializing objects (Thies)

  • Fixed WDDX mem leak when undefined variable is passed in for serialization (Andrei)

  • Fixed double session globals shutdown crash (Andrei)

  • Fixed crash related to ignore_user_abort ini entry (Andrei)

  • Fixed session.auto_start (Sascha)

  • Fixed several problems with output buffering and HEAD requests (Zeev)

  • Fixed HTTP Status code issue with ISAPI module (Zeev)

  • Fixed a problem that prevented $GLOBALS from working properly (Zeev, Zend library)

  • Fixed a crash that would occur if wddx_deserialize did not receive a valid packet (Andrei)

  • Fixed a bugglet when redefining a class at run-time (Andi, Zend Engine)

  • Fixed sem_get() on AIX (Sascha)

  • Fixed fopen() to work with URL’s in Win32 (Andi & Zeev)

  • Fixed include_path for Win32 (Andi, Zend Engine)

  • Fixed bug in ISAPI header sending function (Charles)

  • Fixed memory leak when using undefined values (Andi & Zeev, Zend Engine)

  • Fixed some more class inheritance issues (Zeev, Zend Engine)

  • Fixed Apache build wrt to shared modules on FreeBSD/Linux (Sascha)

  • Fixed mysql_errno() to work with recent versions of MySQL (Zeev)

  • Fixed a problem with define() and boolean values (Zeev)

  • Fixed inclusion of gd/freetype functions (Sascha)

  • Fixed persistency of MHASH_* constants (Sascha)

  • Fixed flushing of cached information to disk in DBA’s DB2 module (Sascha)

  • Fixed is_writeable/is_writable problem; they are both defined now (Andrei)

  • Fixed thread-safety issues in the MySQL module (Zeev)

  • Fixed thread-safe support for dynamic modules (Zeev)

  • Fixed Sybase CT build process (Zeev)

为了解决什么问题

阅读全文 »

有什么变化

新增了什么

  • Made the IMAP module work with PHP 4.0 (Zeev)
  • Added get_class($obj), get_parent_class($obj) and method_exists($obj,“name”) (Andi & Zeev)
  • Added function entries for strip_tags() and similar_text() (Andrei)
  • Ported strtotime() function from PHP 3.0 (Andrei)
  • buildconf now checks your installation (Stig)
  • XML module now built dynamically with --with-xml=shared (Stig)
  • Added a check for freetype.h - fixed build on RedHat 6.0 (Zeev)
  • Ported all remaining date() format options from PHP 3.0 (Andrei)
  • $php_errormsg now works (Andrei)
  • Added locale support for Perl Compatible Regexp functions (Andrei)
  • Informix module ported (Danny)
  • Added patch for reverse lookup table in base64_decode (Sascha) Submitted by [email protected]
  • Added DBA module (Sascha)
  • Added session id detection within REQUEST_URI (Sascha)
  • Added missing E_ error level constants (Zeev, Zend Engine)
  • Gave PHP 4.0’s SNMP extension all the functionality of PHP 3.0.12 (SteveL)

移除了什么

  • Remove --with-shared-apache (Sascha)

修改了什么

  • Win32 builds now include the ODBC module built-in (Zeev)

  • Updated hyperwave module, made it thread safe

  • Updated pdflib module, version 0.6 of pdflib no longer supported

  • Updated fdf module

  • Built-in phpinfo() links are now turned off by default. They can be turned on using the allow_builtin_links INI directive (Zeev)

  • Changed phpinfo() to list modules that have no info function (Zeev)

  • Modified array_walk() function so that the userland callback is passed a key and possible user data in addition to the value (Andrei)

  • Children now inherit their parent’s constructor, if they do not supply a constructor of their own.

  • Apache php_flag values only recognized ‘On’ (case sensitive) - changed to case insensitive (Zeev)

  • Merged in gdttf stuff from PHP 3.0 (Sascha)

  • Merged in PHP 3.0 version of str_replace (Sascha)

  • Merged in HP-UX/ANSI compatibility switch from PHP 3.0 (Sascha)

  • Improved register_shutdown_function() - you may now supply arguments that will be passed to the shutdown function (Zeev)

  • Improved call_user_func() and call_user_method() - they now support passing arguments by reference (Zeev)

  • Improved ISAPI module to supprt large server variables (Zeev)

修复了什么BUG

  • Fixed a problem when sending HTTP/1.x header lines using header() (Zeev)
  • Fixed SYSV-SHM interface (Thies).
  • Fixed ldap_search(), ldap_read() and ldap_list() (Zeev)
  • Fixed Apache information in phpinfo() ([email protected])
  • Fixed usort() and uksort() (Zeev)
  • Fixed md5() in the Apache module (Thies)
  • Fixed sybase_fetch_object() (Zeev)
  • Fixed a problem with include()/require() of URLs (Sascha, Zeev)
  • Fixed a bug in implode() that caused it to corrupt its arguments (Zeev)
  • Fixed various inheritance problems (Andi & Zeev, Zend Engine)
  • Fixed runtime inheritance of classes (parent methods/properties were overriding their children) (Zeev, Zend Engine)
  • Fixed backwards incompatibility with the “new” operator (Andi, Zend Engine)
  • Fixed bugs in uksort() and ksort() sort ordering (Andrei)
  • Fixed a memory leak when using assignment-op operators with lvalue of type string (Zeev, Zend Engine)
  • Fixed a problem in inheritance from classes that are defined in include()d files (Zeev, Zend Engine)
  • Fixed a problem with the PHP error handler that could result in a crash on certain operating systems (Zeev)
  • Fixed a memory leak with switch statement containing return statements (Andi & Zeev, Zend Engine)
  • Fixed a crash problem in switch statements that had a string offset as a conditional (Andi & Zeev, Zend Engine)
  • Imported PHP 3.0 fixes for problem with PHP as a dynamic module and Redhat libc2.1 in zlib module (Stefan)
  • Imported PHP 3.0 fixes for rand() and mt_rand() (Rasmus)
  • Fixed a bug in WDDX that would cause a crash if a number was passed in instead of a variable name (Andrei)
  • Fixed array_walk() to work in PHP 4.0 (Andrei)
  • Fixed rpath handling for utilitites built during Apache build (Sascha)
  • Fixed a bug in sending multiple HTTP Cookies under Apache (Zeev)
  • Fixed implicit connect on the MySQL, mSQL, PostgreSQL and Sybase modules (Zeev)

为了解决什么问题

阅读全文 »