What's new in PHP 7.4?

What's new in PHP 7.4?

4ce755c7f3ddf4e0c92e1aeaeea7677b?s=128

Jachim Coudenys

December 10, 2019
Tweet

Transcript

  1. Zoeterenieweve rsiezientè? Oftewel: kiektekidoa, ‘t is PHP 7.4 Jachim Coudenys

    @coudenysj https://jachim.be jachim.coudenys@combell.group
  2. None
  3. Jachim Coudenys

  4. Deprecations & Removals

  5. Deprecations for PHP 7.4 Functionality to be deprecated in PHP

    7.4. https://wiki.php.net/rfc/deprecations_php_7_4
  6. Deprecations for PHP 7.4 • The real type • Magic

    quotes legacy • array_key_exists() with objects • FILTER_SANITIZE_MAGIC_QUOTES filter • Reflection export() methods • mb_strrpos() with encoding as 3rd argument • implode() parameter order mix • Unbinding $this from non-static closures • hebrevc() function • convert_cyr_string() function • money_format() function • ezmlm_hash() function • restore_include_path() function • allow_url_include ini directive
  7. Deprecate alternate access to array elements and chars in string

    Deprecate curly braces array and string syntax access. https://wiki.php.net/rfc/deprecate_curly_braces_array_access
  8. Deprecate curly braces array $arr = [1, 2, 3]; var_dump($arr{1});

    Deprecated: Array and string offset access syntax with curly braces is deprecated in test.php line 3 int(2) https://3v4l.org/adbHI
  9. Deprecate left-associative ternary operator Deprecate nesting of ternaries without explicit

    use of parentheses. https://wiki.php.net/rfc/ternary_associativity
  10. Deprecate left-associative ternary operator return $a == 1 ? 'one'

    : $a == 2 ? 'two' : $a == 3 ? 'three' : $a == 4 ? 'four' : 'other'; return $a == 1 ? 'one' : ($a == 2 ? 'two' : ($a == 3 ? 'three' : ($a == 4 ? 'four' : 'other'))); return ((($a == 1 ? 'one' : $a == 2) ? 'two' : $a == 3) ? 'three' : $a == 4) ? 'four' : 'other';
  11. Deprecate left-associative ternary operator 1 ? 2 : 3 ?

    4 : 5; // deprecated (1 ? 2 : 3) ? 4 : 5; // ok 1 ? 2 : (3 ? 4 : 5); // ok 1 ?: 2 ? 3 : 4; // deprecated (1 ?: 2) ? 3 : 4; // ok 1 ?: (2 ? 3 : 4); // ok 1 ? 2 : 3 ?: 4; // deprecated (1 ? 2 : 3) ?: 4; // ok 1 ? 2 : (3 ?: 4); // ok 1 ?: 2 ?: 3; // ok (1 ?: 2) ?: 3; // ok 1 ?: (2 ?: 3); // ok https://3v4l.org/H7ebn
  12. Deprecate and remove ext/interbase Deprecate and eventually remove the InterBase

    extension in the Core https://wiki.php.net/rfc/deprecate-and-remove-ext-interbase
  13. Unbundle ext/wddx https://wiki.php.net/rfc/deprecate-and-remove-ext-wddx

  14. WDDX WDDX (Web Distributed Data eXchange) is a programming language-,

    platform- and transport-neutral data interchange mechanism designed to pass data between different environments and different computers. https://en.wikipedia.org/wiki/WDDX
  15. Unbundle ext/recode https://wiki.php.net/rfc/unbundle_recode

  16. Recode This functionality is basically already supported by ext/iconv and

    ext/mbstring. While the two latter extensions rely on POSIX iconv support or libiconv, and the bundled libmbfl, respectively, ext/recode relies on the Recode library which is decomissioned and had its latest release on 22 January 2001.
  17. Improvements & New Features

  18. E_WARNING for invalid containers Raise E_WARNING for array access on

    invalid containers https://wiki.php.net/rfc/notice-for-non-valid-array-container
  19. E_WARNING for invalid containers $var = false; $var[1][2][3][4][5]; // This

    will throw a single E_WARNING, as accessing ($a[1])[2] // is attempting to access a IS_VAR chain that is NULL. // Output would be: // Warning: Variable of type boolean does not accept array offsets https://3v4l.org/QL5Gq
  20. E_WARNING for invalid containers $var = array(123); $var[0][1]; // This

    will throw an E_WARNING, as accessing $a[0] is valid // [1] is accessing an integer as an array. // Output would be: // Warning: Variable of type integer does not accept array offsets https://3v4l.org/v1E9J
  21. E_WARNING for invalid containers $a = [null]; $c = null;

    var_dump($a[0][0] + $c[0]); // This will through 2 E_WARNINGS, First would be $a[0][0] // For the same reason as above, $a[0] is rightfully NULL // and accessing [0] on null is invalid. The second, // would be $c[0] for the same reason. // Output: // int(0) https://3v4l.org/V8qHp
  22. Base Convert improvements Changes to base convert to warn the

    user when incorrect values are passed. Also allow negative numbers to be parsed. https://wiki.php.net/rfc/base_convert_improvements
  23. Base Convert improvements The base_convert family of functions(base_convert, binhex, hexbin

    etc) are very accepting with their input arguments, you can pass any string to to them and they give a best effort of converting it. For example base_convert(“hello world”, 16, 10); will return 237 with no warnings. What this does internally is base_convert(“ed”, 16, 10); https://3v4l.org/3Jbem Also negative numbers simply do not work, eg base_convert(“-ff”, 16, 10); will return 255. (similar to above the “-” gets silently ignored). https://3v4l.org/nTaIL
  24. Base Convert improvements • decbin() - Decimal to binary •

    bindec() - Binary to decimal • decoct() - Decimal to octal • octdec() - Octal to decimal • dechex() - Decimal to hexadecimal • hexdec() - Hexadecimal to decimal
  25. Numeric Literal Separator Enable improved code readability by supporting an

    underscore between digits in numeric literals. https://wiki.php.net/rfc/numeric_literal_separator
  26. Numeric Literal Separator $threshold = 1_000_000_000; // a billion! var_dump($threshold);

    $discount = 135_00; // $135, stored as cents var_dump($discount); $testValue = 107_925_284.88; // scale is hundreds of millions var_dump($testValue); https://3v4l.org/mYEs5
  27. Allow throwing exceptions from __toString() Support throwing exceptions from __toString

    https://wiki.php.net/rfc/tostring_exceptions
  28. Null Coalesce Equal Operator Allow shorthand for self assigning null

    coalesce operator https://wiki.php.net/rfc/null_coalesce_equal_operator
  29. Null Coalesce Equal Operator // The folloving lines are doing

    the same $this->request->data['comments']['user_id'] = $this->request->data['comments']['user_id'] ?? 'value'; // Instead of repeating variables with long names, the equal coalesce operator is used $this->request->data['comments']['user_id'] ??= 'value';
  30. mb_str_split() Split multibyte string https://wiki.php.net/rfc/mb_str_split

  31. Reflection for references Introduces the ReflectionReference class to allow detecting

    references and determining reference equality. https://wiki.php.net/rfc/reference_reflection
  32. New custom object serialization mechanism Introduces new custom object serialization

    mechanism to replace Serializable. https://wiki.php.net/rfc/custom_object_serialization
  33. New custom object serialization mechanism PHP currently provides two mechanisms

    for custom serialization of objects: The __sleep()/__wakeup() magic methods, as well as the Serializable interface.
  34. New custom object serialization mechanism The proposed serialization mechanism tries

    to combine the generality of Serializable with the implementation approach of __sleep()/__wakeup(). Two new magic methods are added: // Returns array containing all the necessary state of the object. public function __serialize(): array; // Restores the object state from the given data array. public function __unserialize(array $data): void;
  35. Change the precedence of the concatenation operator Update the precedence

    of concatenation to be inferior to addition and subtraction https://wiki.php.net/rfc/concatenation_precedence
  36. Change the precedence of the concat operator echo "sum: "

    . $a + $b; // current behavior: evaluated left-to-right echo ("sum: " . $a) + $b; // desired behavior: addition and subtraction have a higher precendence echo "sum :" . ($a + $b); https://3v4l.org/i4pI7
  37. Types

  38. Covariant Returns and Contravariant Parameters https://wiki.php.net/rfc/covariant-returns-and-contravariant-parame ters

  39. Covariant Returns and Contravariant Parameters • a parameter type can

    be substituted for one of its super-types • a return type can substitute a sub-type.
  40. Covariant Returns and Contravariant Parameters interface A { function m(B

    $z); } interface B extends A { // permitted function m($z): A; } interface X { function m(Y $z): X; } interface Y extends X { // not permitted but type-safe function m(X $z): Y; }
  41. Typed Properties 2.0 Add support for typed properties, including static

    properties and references to typed properties. https://wiki.php.net/rfc/typed_properties_v2
  42. Typed Properties class User { /** @var int $id */

    private $id; /** @var string $name */ private $name; public function __construct(int $id, string $name) { $this->id = $id; $this->name = $name; } public function getId(): int { return $this->id; } public function setId(int $id): void { $this->id = $id; } public function getName(): string { return $this->name; } public function setName(string $name): void { $this->name = $name; } }
  43. Typed Properties class User { public int $id; public string

    $name; public function __construct(int $id, string $name) { $this->id = $id; $this->name = $name; } }
  44. Cool stuff!

  45. Spread Operator in Array Expression https://wiki.php.net/rfc/spread_operator_for_array

  46. Spread Operator in Array Expression $parts = ['apple', 'pear']; $fruits

    = ['banana', 'orange', ...$parts, 'watermelon']; // ['banana', 'orange', 'apple', 'pear', 'watermelon'];
  47. Arrow functions 2.0 Adds short closures / arrow functions. https://wiki.php.net/rfc/arrow_functions_v2

  48. fn(parameter_list) => expr

  49. Arrow functions $extended = function ($c) use ($callable, $factory) {

    return $callable($factory($c), $c); }; // with arrow function: $extended = fn($c) => $callable($factory($c), $c);
  50. Arrow functions $this->existingSchemaPaths = array_filter($paths, function ($v) use ($names) {

    return in_array($v, $names); }); // with arrow function $this->existingSchemaPaths = array_filter($paths, fn($v) => in_array($v, $names));
  51. FFI - Foreign Function Interface https://wiki.php.net/rfc/ffi

  52. FFI - Foreign Function Interface <?php // create FFI object,

    loading libc and exporting function printf() $ffi = FFI::cdef( "int printf(const char *format, ...);", // this is a regular C declaration "libc.so.6"); // call C's printf() $ffi->printf("Hello %s!\n", "world"); ?>
  53. Security

  54. Always available hash extension Proposes to make the hash extension

    available to every build of PHP. https://wiki.php.net/rfc/permanent_hash_ext
  55. Always available hash extension Make the hash extension (`ext/hash`) always

    available, similar to the `date`, `spl` & `pcre` extensions.
  56. Password Hash Registry Make the mechanisms used by password_hash/verify/etc… extensible

    by other modules. https://wiki.php.net/rfc/password_registry
  57. Password Hash Registry > print_r(password_algos()); Array ( [0] => "2y"

    // Ident for "bcrypt" [1] => "argon2i" [2] => "argon2id" )
  58. Argon2 support from sodium Provide password_hash https://wiki.php.net/rfc/sodium.argon.hash

  59. Improve openssl_random_pseudo_bytes() Proposes making openssl_random_pseudo_bytes https://wiki.php.net/rfc/improve-openssl-random-pseudo-bytes

  60. Improve openssl_random_pseudo_bytes() Throws exception instead of empty string/false on failure

  61. Escape PDO “?” parameter placeholder Changes to PDO to allow

    using operators containing “?” with pdo_pgsql, most commonly the JSON key exists “?” operator. https://wiki.php.net/rfc/pdo_escape_placeholders
  62. Escape PDO “?” parameter placeholder $stmt = $pdo->prepare('SELECT * FROM

    tbl WHERE json_col ?? ?'); $stmt->execute(['foo']); SELECT * FROM tbl WHERE json_col ? 'foo'
  63. Performance & Garbage Collection

  64. weakrefs https://wiki.php.net/rfc/weakrefs

  65. weakrefs Weak references allow the programmer to retain a reference

    to an object which does not prevent the object from being destroyed. They are useful for implementing cache like structures.
  66. weakrefs WeakReference { public __construct ( void ) public static

    create ( object $referent ) : WeakReference public get ( void ) : ?object } $obj = new stdClass; $weakref = WeakReference::create($obj); var_dump($weakref->get()); unset($obj); var_dump($weakref->get()); https://3v4l.org/hFqPp
  67. Preloading Preload PHP functions and classes once and use them

    in the context of any future request without overhead. https://wiki.php.net/rfc/preload
  68. OPCache on steroids

  69. OPCache • Skips compiling step • Still needs to link

    all classes on every request ◦ Class inheritance • Timestamp validation (optional)
  70. Preloading • On server startup: compile and link everything in

    memory ◦ Manual process via “preload file” • Everything is available for all following requests • Preloaded classes are now as fast as native function (strlen, \Exception, etc…) • Server restart is needed to “refresh” code
  71. Preloading Config • opcache.preload=/path/to/preload.php • opcache_compile_file()

  72. Unlinked classes aren’t preloaded

  73. Preloading in the wild • https://github.com/brendt/laravel-preload/blob/master/preload.php • https://symfony.com/blog/new-in-symfony-4-4-preloading-symfony-applicatio ns-in-php-7-4 //

    var/cache/dev/srcApp_KernelDevDebugContainer.preload.php // This file has been auto-generated by the Symfony Dependency Injection Component // You can reference it in the "opcache.preload" php.ini setting on PHP >= 7.4 when preloading is desired use Symfony\Component\DependencyInjection\Dumper\Preloader; require dirname(__DIR__, 3).'/vendor/autoload.php'; require __DIR__.'/ContainerZxvZ783/srcApp_KernelDevDebugContainer.php'; $classes = []; $classes[] = 'App\Kernel'; Preloader::preload($classes);
  74. Caveats • “Full server” (fpm) ◦ php.ini setting • Server

    restart
  75. Composer • https://github.com/composer/composer/issues/7777#issuecomment-44026 8416 • https://github.com/composer/composer/issues/7777 You are welcome to

    keep the discussion going here as a central point for people interested in the topic to coordinate. But just to be clear, I am fairly confident that in the near future we are not going to add anything to Composer relating to preloading. If in a year it turns out - after people have been playing with it - that there is something Composer is uniquely positioned to really help with, we can revisit. For now it seems to me much more like an application/deployment concern than a dependency management one.
  76. None
  77. Zotjes é?

  78. Upgrading / Migrating • https://github.com/php/php-src/blob/PHP-7.4/UPGRADING • https://www.php.net/manual/en/migration74.php

  79. http://phpversions.info/shared-hosting/

  80. Resources • https://wiki.php.net/rfc#php_74 • https://symfony.com/blog/new-in-symfony-4-4-preloading-symfony-applicatio ns-in-php-7-4 • https://www.google.com/search?q=google+php+7.4

  81. Bedankté! https://joind.in/event/php-wvl-d ecember-meetup-at-bits-of-love/ zoeterenieweversieziente Jachim Coudenys @coudenysj jachim.be