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

Jumping into PHP 7

Jumping into PHP 7

We will look at the biggest issues you could face when migrating a PHP 5 project to PHP 7 as well as the new features.

Bob Majdak Jr

March 08, 2016
Tweet

More Decks by Bob Majdak Jr

Other Decks in Programming

Transcript

  1. Flat Out Gone ereg call_user_method[_array] set_socket_blocking all postscript 1 functions

    (imageeps*) $HTTP_RAW_POST_DATA <%, <script language="php"> preg_match call_user_func[_array] stream_set_blocking migrate to TTF for rendering fonts file_get_contents("php://input") <?php // :p Extension: MySQL - Jump ship and migrate to PDO... or be lazy and migrate to MySQL Improved by adding "i" to all your functional calls... mysql_connect => mysqli_connect. Strongly consider restructuring for OOP. Extension: MSSQL - Migrate to PDO or SQLSRV.
  2. Error and Exception Handling A lot of things that used

    to throw fatal errors now throw catchable Errors. You are now able to catch a lot more things than you were able to previous. May seeing some uncaught errors flying around afterwards. Fatal Error: Cannot declare class Error.
  3. Error and Exception Handling (cont.) interface Throwable; • Exception implements

    Throwable; ◦ Exceptions as usual. You should not notice [m]any differences with your existing error handlers for past exceptions. • Error implements Throwable; ◦ More kinda serious exceptions thrown by the engine instead of the old errors that you could do nothing about but laugh at.
  4. Bane of E_STRICT E_STRICT still exists, but it is currently

    empty. All things that used to spam E_STRICT things have been "downgraded". • E_DEPRECATED for old things. • E_NOTICE for dumb things you did. • E_WARNING for dumber things you did.
  5. Changes to Dynamic Variable Resolution $$Val['Key'] ${$Val['Key']} $Object->$Property['Key'] $Object->{$Property['Key']} ($$Val)['Key'];

    ($Object->$Property)['Key']; Variable resolution is now left-to-right precedence. This means you WILL experience problems if you were not very explicit with your magical magic. This also means they are going to read really weird. Solution: Always Be Explicit... and TBH... just avoid this feature unless it is super clever.
  6. Changes to Yielding (Generators) echo yield -1; echo (yield) -

    1; // wat echo yield (-1); // thur we go Yield is now a right-to-left precedence keyword. Some things that read really odd before should read a bit nicer. Yield can now also yield another generator now to extend its iteration train. Yield can now also return a final value after-the-fact, retrievable by the GetResult method.
  7. Changes to FOREACH() No longer moves the internal array pointer.

    Now operates on a "copy" of the array while doing by-value looping (while still seeming to respect copy-on-write behaviour). This means appending during foreach() will not result in an extended loop. Appending during foreach() while doing a by-reference loop will now extend the loop consistently/properly. https://gist.github.com/bobmajdakjr/7553df62287cd534f31a
  8. Changes to LIST() The list() construct is no longer able

    to split strings for you. Use str_split. The order of items has been normalised when appending onto an existing array with the []'s in the list. • list($A[], $A[], $A[]) = [1, 2, 3]; • PHP 5: $A = [ 3, 2, 1 ]; • PHP 7: $A = [ 1, 2, 3];
  9. Changes to JSON handling The JSON Parser was changed under

    the hood which results in a few changes in how it handles floats. Less leeway on how bad you can malform them. The decimal cannot be the last thing anymore, in normal notation and science notation: • json_decode('42.'); // NULL • json_decode('42.e42'); // NULL Cut the decimal point out or append a zero: • '42', '42.0' • '42e42', '42.0e42'
  10. General Changes to Function Definitions Multiple arguments with the same

    name are no longer valid and is fatal. • function Whatevs($Thing, $Trash, $Trash, $Trash) { func_get_args now tracks the reference of the arguments rather than the value, but only if they were defined by the function signature...
  11. General Data Type Changes (Integers) Negative bit shifts are no

    longer valid and will throw an ArithmeticError. • $Result = 4 << -2; • $Result = 4 << $CalculatedShift; // :( Shifting too wide will always result in 0. • $Result = 1 << 9001; • int(0) Division by 0... Prepare your WTFing... • var_dump(3/0); // float(INF) (and a E_WARNING) • var_dump(-3/0); // float(-INF) (and a E_WARNING) • var_dump(0/0); // float(NAN) (and a E_WARNING) • var_dump(0%0); // CATCHABLE FATAL ERRRRRRRERRRR • used to just be warnings and bool(false) for all the things...
  12. General Data Type Changes (Strings) is_numeric() no longer claims hex

    values are numeric. • "is it generic human understandable" ◦ "15" yes. ◦ "0xf" no. • $Int = filter_var('0xf', FILTER_VALIDATE_INT, FILTER_FLAG_ALLOW_HEX); • $Int = hexdec('0xf');
  13. General Data Type Changes (Objects) Using the Store-By-Reference operator is

    no longer valid when instantiating new objects. • $Object =& new Whatever; • Objects are already PBR... you do not want to pass an object by reference reference. If you think you do, you don't.
  14. Scalar Type Hints Classes, Interfaces, and Arrays... • Integers (int)

    • Floats (float) • Booleans (bool) • Strings (string) • The Object Doing It (self) Unfortunately not properly nullable yet... but... function Whatever(Type $Arg): ReturnType { }
  15. Scalar Type Hints (cont.) By default type hints are "coerced"

    or weak typed. Files can declare they want super strict typing by adding a declaration at the top of the file. This (strict types) only affects the file in question and not calls to functions within the file from outside the file. The only way to allow "something or null" is with =NULL on the arg. There is no valid syntax like "?int" yet to mark it nullable. This also has the side effect of making it optional... which may not actually be desirable...
  16. NULL Coalescing Operator (??) Is it defined and not NULL?

    Then have it else have this other thing. Chainable, reading from left to right. Similar to the Ternary operator. It is safe to use on array keys which may not exist, similar to isset().
  17. Spaceship Operator (<=>) Less Than, Equal To, Greater Than all

    in one. Returns -1, 0, or 1, depending on the result of the expression. "Troolean" Allows you to quickly write simple sorts.
  18. Like normal constants. Only... arrays. • define('SITELIST', ['one','two','three']); • echo

    SITELIST[0]; Numerical or Associative, whatevs. Constant Arrays
  19. Anonymous Objects Just like anonymous functions, you can now defined

    anonymous classes to create anonymous objects. • $Object = new class { public function Wut() { return 'Wut'; } }; • echo $Object->Wut(), PHP_EOL; Please um... use... sparingly...
  20. Unicode Codepoint Escape Sequence You can now generate UTF characters

    within strings with the \u{} escape sequence. It takes the codepage value in hex.
  21. So assert() was already a thing in PHP, but it

    has been upgraded. Allows you to include debugging assertions within the code, with the ability to toggle them off so they have zero performance impact on production. Allows you to throw exceptions for things you may need to debug, but may not actually be fatal to the process. This is a multistep process. Expectations Via Assertions
  22. Expectations can be configured to either be Fatal, Warnings, or

    Silent. This is done via two different INI directives. • assert.exception = 0 or 1 (default 0) ◦ 0 = Run the assertion but instead of throwing the exception, spew the exception as a Warning ◦ 1 = Run the assertion and exception it hard if it fails. ◦ Can be set via ini_set(). • zend.assertions = -1, 0, or 1 (default 1) ◦ 1 = Compile and Execute the assertion. (dev mode) ◦ 0 = Compile but skip the assertion. ◦ -1 = Skip it completely for Zero Impact. (prod mode) ◦ Cannot be set via ini_set(). Expectations Via Assertions (cont.)
  23. Closure Call Binding Anonymous functions / closures have had an

    upgrade to make it easier to rebind the value of $this within the function via the Call method.
  24. Looser Restricted Word Restrictions You can now use almost all

    keywords as method names, with the exception of "class". Rejoyce, but also be careful. public function private() { } // lol - now valid.
  25. Cryptographic Safe RNG (random_bytes, random_int) Generates random numbers using the

    proper cryptographically secure (as we know it) APIs on the various platforms. • Windows: CryptGenRandom() • Linux: getrandom() • Fallback: /dev/urandom
  26. Procedural Regex with preg_replace_callback_array This function allows you to define

    a list of patterns to apply to the source data one at a time. Nice for shorthanding. Array of patterns where the key is the pattern and the value is the callback to execute. The return of the callback is what gets subbed in for the pattern.
  27. New Unicode Character Testing API (IntlChar) Everything you ever needed

    to know about UTF characters and a lot of things you didn't want to know. Kinda an odd API... all static... With it though you can test anything about a character to determine how you should treat it.
  28. Deprecated Features • PHP 4 style Constructors. ◦ class Whatever

    { public function Whatever() { } } • Calling static methods unstatically. ◦ They have no $this. ◦ Don't wait though on these, fix them now. • Custom salt param on password_hash ◦ Kinda a step backwards, but they think they are protecting you from yourself. • Stream SSL Contexts: capture_session_meta ◦ Session meta available via stream_get_meta_data
  29. FIN Bob Majdak Jr @bobmagicii Dallas PHP - March 2016

    These Slides https://goo.gl/wDX0eP Code In Slides https://goo.gl/EpCxCT