Upgrade to Pro — share decks privately, control downloads, hide ads and more …

What's new in PHP 7.4?

What's new in PHP 7.4?

Jachim Coudenys

December 10, 2019
Tweet

More Decks by Jachim Coudenys

Other Decks in Programming

Transcript

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

    7.4. https://wiki.php.net/rfc/deprecations_php_7_4
  2. 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
  3. 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
  4. 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
  5. Deprecate left-associative ternary operator Deprecate nesting of ternaries without explicit

    use of parentheses. https://wiki.php.net/rfc/ternary_associativity
  6. 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';
  7. 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
  8. 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
  9. 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
  10. 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.
  11. 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
  12. 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
  13. 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
  14. 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
  15. 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
  16. 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
  17. 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
  18. Numeric Literal Separator Enable improved code readability by supporting an

    underscore between digits in numeric literals. https://wiki.php.net/rfc/numeric_literal_separator
  19. 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
  20. Null Coalesce Equal Operator Allow shorthand for self assigning null

    coalesce operator https://wiki.php.net/rfc/null_coalesce_equal_operator
  21. 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';
  22. Reflection for references Introduces the ReflectionReference class to allow detecting

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

    mechanism to replace Serializable. https://wiki.php.net/rfc/custom_object_serialization
  24. 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.
  25. 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;
  26. 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
  27. 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
  28. 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.
  29. 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; }
  30. 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
  31. 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; } }
  32. Typed Properties class User { public int $id; public string

    $name; public function __construct(int $id, string $name) { $this->id = $id; $this->name = $name; } }
  33. Spread Operator in Array Expression $parts = ['apple', 'pear']; $fruits

    = ['banana', 'orange', ...$parts, 'watermelon']; // ['banana', 'orange', 'apple', 'pear', 'watermelon'];
  34. Arrow functions $extended = function ($c) use ($callable, $factory) {

    return $callable($factory($c), $c); }; // with arrow function: $extended = fn($c) => $callable($factory($c), $c);
  35. 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));
  36. 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"); ?>
  37. Always available hash extension Proposes to make the hash extension

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

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

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

    // Ident for "bcrypt" [1] => "argon2i" [2] => "argon2id" )
  41. 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
  42. Escape PDO “?” parameter placeholder $stmt = $pdo->prepare('SELECT * FROM

    tbl WHERE json_col ?? ?'); $stmt->execute(['foo']); SELECT * FROM tbl WHERE json_col ? 'foo'
  43. 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.
  44. 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
  45. 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
  46. OPCache • Skips compiling step • Still needs to link

    all classes on every request ◦ Class inheritance • Timestamp validation (optional)
  47. 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
  48. 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);
  49. 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.