SlideShare a Scribd company logo
Migrating to PHP 7
John Coggeshall – International PHP Conference, 2016
Berlin, Germany
@coogle, john@coggeshall.org
Who’s This Guy?
• The Author of ext/tidy
• (primary) Author in (almost) 5 books on PHP going from PHP 4 to
PHP 7
• Speaking at conferences for a long time
!!!!!
circa 2004 today
Major Concerns when Migrating to PHP 7
• Error Handling
• Variable Handling
• Control Structure Changes
• Removed Features / Changed Functions
• Newly Deprecated Behaviors
• This talk will not cover every single detail of the changes in PHP 7.
That’s what Migration Documentation is for:
http://php.net/manual/de/migration70.php
Error Handling
• One of the biggest breaks you may have to deal with migrating to
PHP 7 will be error handling
• Especially when using Custom Error Handlers
• Many fatal / recoverable errors from PHP 5 have been converted
to exceptions
• Major Break: The callback for set_exception_handler() is not
guaranteed to receive Exception objects
Fixing Exception Handlers
<?php
function my_handler(Exception $e)
{
/* ... */
}
<?php
function my_handler(Throwable $e)
{
/* ... */
}
PHP 5 PHP 7
Other Internal Exceptions
• Some internal class constructors in PHP 5 would create objects in
unusable states rather than throw exceptions
• In PHP 7 all class constructors throw exceptions
• Notably this was a problem in some of the Reflection Classes
You should always be prepared to handle an exception thrown from
PHP 7 internal classes in the event something goes wrong
Parser Errors
• In PHP 5, parsing errors (for instance, from an include_once
statement) would cause a fatal error
• In PHP 7 parser errors throw the new ParseError exception
Again, your custom error handlers and exception handlers may need
updating to reflect this new behavior
E_STRICT is Dead
Situation New Behavior
Indexing by a Resource E_NOTICE
Abstract Static Methods No Error
”Redefining” a constructor No Error
Signature mismatch during inheritance E_WARNING
Same (compatible) property used in two
traits
No Error
Accessing a static property non-statically E_NOTICE
Only variables should be assigned by
reference
E_NOTICE
Only variables should be passed by reference E_NOTICE
Calling non-static methods statically E_DEPRECATED
Indirect Variables, Properties, Methods
• In PHP 5 complex indirect access to variables, properties, etc. was
not consistently handled.
• PHP 7 addresses these inconsistencies, at the cost of backward
compatibility
Typically most well-written code will not be affected by this.
However, if you have complicated indirect accesses you may hit
this.
Indirect Variables, Properties, Methods
Expression PHP 5 PHP 7
$$foo[‘bar’][‘baz’] ${$foo[‘bar’][‘baz’]} ($$foo)[‘bar’][‘baz’]
$foo->$bar[‘baz’] $foo->{$bar[‘baz’]} ($foo->$bar)[‘baz’]
$foo->$bar[‘baz’]() $foo->{$bar[‘baz’]}() ($foo->$bar)[‘baz’]()
Foo::bar[‘baz’]() Foo::{$bar[‘baz’]}() (Foo::$bar)[‘baz’]()
If you are using any of the expression patterns on the left
column the code will need to be updated to the middle
“PHP 5” column to be interpreted correctly.
list() Mayhem
• There is a lot of code out there that takes the assignment order of
the list() statement for granted:
<?php
list($x[], $x[]) = [1, 2];
// $x = [2, 1] in PHP 5
// $x = [1, 2] in PHP 7
• This was never a good idea and you should not rely on the order in
this fashion.
list() Mayhem
• Creative use of the list() statement with empty assignments will
also now break
<?php
// Both will now break in PHP 7
list() = $array;
list(,$x) = $array;
list() Mayhem
• Finally, list() can no longer be used to unpack strings.
<?php
list($a, $b, $c) = “abc”;
// $a = “a” in PHP 5, breaks in PHP 7
Subtle foreach() changes – Array Pointers
• In PHP 5 iterating over an array using foreach() would cause the
internal array pointer to move for each iteration
<?php
$a = [1, 2]
foreach($a as &$val) {
var_dump(current($a));
}
// Output in PHP 5:
// int(1)
// int(2)
// bool(false)
<?php
$a = [1, 2]
foreach($a as &$val) {
var_dump(current($a));
}
// Output in PHP 7:
// int(1)
// int(1)
// int(1)
Subtle foreach() changes – References
This subtle change may break code that modifies arrays by
reference during an iteration of it
<?php
$a = [0];
foreach($a as &$val) {
var_dump($val);
$a[1] = 1;
}
// Output in PHP 5
// int(0)
<?php
$a = [0];
foreach($a as &$val) {
var_dump($val);
$a[1] = 1;
}
// Output in PHP 7
// int(0)
// int(1)
In PHP 5 you couldn’t add to an array, even when passing it by
reference and iterate over them in the same block
Integer handler changes
• Invalid Octal literals now throw parser errors instead of being
silently ignored
• Bitwise shifts of integers by negative numbers now throws an
ArithmeticError
• Bitwise shifts that are out of range will now always be int(0)
rather than being architecture-dependent
Division By Zero
• In PHP 5 Division by Zero would always cause an E_WARNING and
evaluate to int(0), including attempting to do a modulus (%) by
zero
• In PHP 7
• X / 0 == float(INF)
• 0 / 0 == float(NaN)
• Attempting to do a modulus of zero now causes a
DivisionByZeroError exception to be thrown
Hexadecimals and Strings
• In PHP 5 strings that evaluated to hexadecimal values could be
cast to numeric values
• I.e. (int)“0x123” == 291
• In PHP 7 strings are no longer directly interpretable as numeric
values
• I.e. (int)”0x123” == 0
• If you need to convert a string hexadecimal value to its integer
equivalent you can use filter_var() with the FILTER_VALIDATE_INT
and FILTER_FLAG_ALLOW_HEX options to convert it to an integer
value.
Calls from Incompatible Contexts
• Static calls made to a non-static method with an incompatible
context (i.e. calling a non-static method statically in a completely
unrelated class) has thrown a E_DEPRECATED error since 5.6
• I.e. Class A calls a non-static method in Class B statically
• In PHP 5, $this would still be defined pointing to class A
• In PHP 7, $this is no longer defined
yield is now right associative
• In PHP 5 the yield construct no longer requires parentheses and
has been changed to a right associative operator
<?php // PHP 5
echo yield -1; // (yield) – 1;
yield $foo or die // yield ($foo or die)
<?php // PHP 7
echo yield -1; // yield (-1)
yield $foo or die // (yield $foo) or die;
Misc Incompatibilities
• There are a number of other (smaller) incompatibilities between
PHP 5 and PHP 7 worth mentioning
• ASP-style tags <% %> have been removed
• <script language=“php”> style tags have been removed
• Assigning the result of the new statement by reference is now fatal error
• Functions that have multiple parameters with the same name is now a
compile error
• switch statements with multiple default blocks is now a compile error
• $HTTP_RAW_POST_DATA has been removed in favor of php://input
• # comments in .ini files parsed by PHP are no longer supported (use
semicolon)
• Custom session handlers that return false result in fatal errors now
Removed Functions
• Numerous functions have been removed in PHP 7 and replaced
with better equivalents where appropriate
Variable Functions
call_user_method()
call_user_method_array()
Mcrypt
mcrypt_generic_end()
mcrypt_ecb()
mcrypt_cbc()
mcrypt_cfb()
mcrypt_ofb()
Intl
datefmt_set_timezone_id()
IntlDateFormatter::setTimeZoneId()
System
set_magic_quotes_runtime()
magic_quotes_runtime()
set_socket_blocking()
dl() (in PHP-FPM)
=
GD
imagepsbbox()
imagepsencodefont()
imagepsextendfont()
imagepsfreefont()
imagepsloadfont()
imagepsslantfont()
imagepstext()
• Removed Extensions: ereg, mssql, mysql, sybase_ct
Removed Server APIs (SAPIs) and extensions
• Numerous Server APIs (SAPIs) have been removed from PHP 7:
• aolserver
• apache
• apache_hooks
• apache2filter
• caudium
• continunity
• isapi
• milter
• nsapi
• phttpd
• pi3web
• roxen
• thttpd
• tux
• webjames
Deprecated Features
• A number of things have been deprecated in PHP 7, which means
they will now throw E_DEPRECATED errors if you happen to be
using them in your code
• PHP 4 style constructors
• Static calls to non-static methods
• Passing your own salt to the password_hash() function
• capture_session_meta SSL context option
• For now these errors can be suppressed (using the @ operator) but
the code should be updated as necessary.
Changes to Core Functions
• When migrating from PHP 5 to PHP 7 there are a few functions
that have changed behaviors worth noting
• mktime() and gmmktime() no longer accept the $is_dst parameter
• preg_replace() no longer supports the /e modifier and
preg_replace_callback() must now be used
• setlocale() no longer accepts strings for the $category parameter. The
LC_* constants must be used
• substr() now returns an empty string if then $string parameter is as
long as the $start parameter value.
Name Conflicts
• There are a lot of new things in PHP 7 that didn’t exist in PHP 5
• New Functions
• New Methods
• New Classes
• New Constants
• New Exceptions
• You should review the PHP Migration documentation for what’s
been added to determine if any code you’ve written now conflicts
with something internal to PHP 7
• For example, do you have an IntlChar class in your application?
Thank you!
John Coggeshall
john@coggeshall.org, @coolge

More Related Content

What's hot (20)

PDF
Design attern in php
Filippo De Santis
 
ODP
Object Oriented Design Patterns for PHP
RobertGonzalez
 
PPSX
PHP Comprehensive Overview
Mohamed Loey
 
PDF
Yapc::NA::2009 - Command Line Perl
Bruce Gray
 
PDF
Php Crash Course - Macq Electronique 2010
Michelangelo van Dam
 
PPT
PHP
sometech
 
PPT
9780538745840 ppt ch01 PHP
Terry Yoast
 
PPT
9780538745840 ppt ch02
Terry Yoast
 
PDF
Flowex - Railway Flow-Based Programming with Elixir GenStage.
Anton Mishchuk
 
PDF
PHP traits, treat or threat?
Nick Belhomme
 
PDF
STC 2016 Programming Language Storytime
Sarah Kiniry
 
PPTX
php basics
Anmol Paul
 
PPT
PHP - Introduction to PHP
Vibrant Technologies & Computers
 
PDF
Php tutorial
Mohammed Ilyas
 
PPT
Introduction to php php++
Tanay Kishore Mishra
 
KEY
php app development 1
barryavery
 
PPTX
Php basics
Jamshid Hashimi
 
PPTX
PHP 7 Crash Course
Colin O'Dell
 
Design attern in php
Filippo De Santis
 
Object Oriented Design Patterns for PHP
RobertGonzalez
 
PHP Comprehensive Overview
Mohamed Loey
 
Yapc::NA::2009 - Command Line Perl
Bruce Gray
 
Php Crash Course - Macq Electronique 2010
Michelangelo van Dam
 
9780538745840 ppt ch01 PHP
Terry Yoast
 
9780538745840 ppt ch02
Terry Yoast
 
Flowex - Railway Flow-Based Programming with Elixir GenStage.
Anton Mishchuk
 
PHP traits, treat or threat?
Nick Belhomme
 
STC 2016 Programming Language Storytime
Sarah Kiniry
 
php basics
Anmol Paul
 
PHP - Introduction to PHP
Vibrant Technologies & Computers
 
Php tutorial
Mohammed Ilyas
 
Introduction to php php++
Tanay Kishore Mishra
 
php app development 1
barryavery
 
Php basics
Jamshid Hashimi
 
PHP 7 Crash Course
Colin O'Dell
 

Viewers also liked (20)

PDF
Disntinciones
Aflora Consulting
 
PPT
Presentación
gbarbuto
 
PDF
IRCA 2020-OHSMS Lead Auditor training-A16830
Laxman Waykar
 
PDF
Nueva UNE ISO 9001:2015
CNI. -Consulting, Networking, Innovation-
 
PPTX
Sap pp parte3
Erasmo Rodríguez Quijada
 
PDF
Instructivo mcbc valorizacion stocks
ricardopabloasensio
 
PPTX
(BPI-II) Unidad 14 - ( Planificación producción -PP) - transacciones
Sebastian Triviño Ortega
 
PPTX
Iso 22716 Aplicación Practica de la Norma
pgomezlobo
 
PDF
Transacciones de visualizacion de stock doc
ricardopabloasensio
 
PPT
Kpi for internal audit
solutesarrobin
 
PDF
planificacion-de-necesidades-sobre-consumo
JUVER ALFARO
 
DOCX
Internal audit manager performance appraisal
collinsbruce43
 
PDF
Plantilla gerencia-de-proyectos
David Toyohashi
 
PPT
Sap mm
ediaz9
 
PDF
Normas (estándares) ISO relativas a TICs
EOI Escuela de Organización Industrial
 
PPT
Planificación de Requerimientos de Material (MRP)
judadd
 
PDF
Cosmetic gmp induction training
Mike Izon
 
PPTX
GMP - ISO 22716
Tadej Feregotto
 
PPTX
NORMA ISO 90003
ANYELISTOVAR
 
PDF
Las normas su importancia y evolucion
Zitec Consultores
 
Disntinciones
Aflora Consulting
 
Presentación
gbarbuto
 
IRCA 2020-OHSMS Lead Auditor training-A16830
Laxman Waykar
 
Instructivo mcbc valorizacion stocks
ricardopabloasensio
 
(BPI-II) Unidad 14 - ( Planificación producción -PP) - transacciones
Sebastian Triviño Ortega
 
Iso 22716 Aplicación Practica de la Norma
pgomezlobo
 
Transacciones de visualizacion de stock doc
ricardopabloasensio
 
Kpi for internal audit
solutesarrobin
 
planificacion-de-necesidades-sobre-consumo
JUVER ALFARO
 
Internal audit manager performance appraisal
collinsbruce43
 
Plantilla gerencia-de-proyectos
David Toyohashi
 
Sap mm
ediaz9
 
Normas (estándares) ISO relativas a TICs
EOI Escuela de Organización Industrial
 
Planificación de Requerimientos de Material (MRP)
judadd
 
Cosmetic gmp induction training
Mike Izon
 
GMP - ISO 22716
Tadej Feregotto
 
NORMA ISO 90003
ANYELISTOVAR
 
Las normas su importancia y evolucion
Zitec Consultores
 
Ad

Similar to Migrating to PHP 7 (20)

PDF
What To Expect From PHP7
Codemotion
 
PDF
Preparing code for Php 7 workshop
Damien Seguy
 
PPTX
Peek at PHP 7
John Coggeshall
 
PDF
Damien seguy php 5.6
Damien Seguy
 
ODP
The why and how of moving to php 5.4
Wim Godden
 
PDF
Last train to php 7
Damien Seguy
 
PPTX
Php7 HHVM and co
weltling
 
PPTX
Php7 hhvm and co
Pierre Joye
 
PPTX
PHP from soup to nuts Course Deck
rICh morrow
 
PDF
Php7 傳說中的第七隻大象
bobo52310
 
PDF
Php 7.2 compliance workshop php benelux
Damien Seguy
 
PDF
PHP7: Hello World!
Pavel Nikolov
 
PPTX
Unit 5-PHP Declaring variables, data types, array, string, operators, Expres...
DRambabu3
 
PDF
Giới thiệu PHP 7
ZendVN
 
PDF
Preparing for the next PHP version (5.6)
Damien Seguy
 
PPTX
Zephir - A Wind of Change for writing PHP extensions
Mark Baker
 
PPTX
Flying under the radar
Mark Baker
 
PPTX
PHP 7
Joshua Copeland
 
PDF
What's new with PHP7
SWIFTotter Solutions
 
PDF
The why and how of moving to php 7
Wim Godden
 
What To Expect From PHP7
Codemotion
 
Preparing code for Php 7 workshop
Damien Seguy
 
Peek at PHP 7
John Coggeshall
 
Damien seguy php 5.6
Damien Seguy
 
The why and how of moving to php 5.4
Wim Godden
 
Last train to php 7
Damien Seguy
 
Php7 HHVM and co
weltling
 
Php7 hhvm and co
Pierre Joye
 
PHP from soup to nuts Course Deck
rICh morrow
 
Php7 傳說中的第七隻大象
bobo52310
 
Php 7.2 compliance workshop php benelux
Damien Seguy
 
PHP7: Hello World!
Pavel Nikolov
 
Unit 5-PHP Declaring variables, data types, array, string, operators, Expres...
DRambabu3
 
Giới thiệu PHP 7
ZendVN
 
Preparing for the next PHP version (5.6)
Damien Seguy
 
Zephir - A Wind of Change for writing PHP extensions
Mark Baker
 
Flying under the radar
Mark Baker
 
What's new with PHP7
SWIFTotter Solutions
 
The why and how of moving to php 7
Wim Godden
 
Ad

More from John Coggeshall (20)

PPTX
Virtualization for Developers
John Coggeshall
 
PPTX
ZF2 Modules: Events, Services, and of course, modularity
John Coggeshall
 
PPT
PHP Development for Google Glass using Phass
John Coggeshall
 
PPTX
Virtualization for Developers
John Coggeshall
 
PPTX
Development with Vagrant
John Coggeshall
 
PPTX
Introduction to Zend Framework 2
John Coggeshall
 
PPTX
10 things not to do at a Startup
John Coggeshall
 
PPTX
Virtualization for Developers
John Coggeshall
 
PPTX
Puppet
John Coggeshall
 
PPT
Building PHP Powered Android Applications
John Coggeshall
 
PPT
Ria Applications And PHP
John Coggeshall
 
PPT
Beyond the Browser
John Coggeshall
 
PPT
Apache Con 2008 Top 10 Mistakes
John Coggeshall
 
PPT
Ria Development With Flex And PHP
John Coggeshall
 
PPT
Top 10 Scalability Mistakes
John Coggeshall
 
PPT
Enterprise PHP: A Case Study
John Coggeshall
 
PPT
Building Dynamic Web Applications on i5 with PHP
John Coggeshall
 
PPT
PHP Security Basics
John Coggeshall
 
PPT
Migrating from PHP 4 to PHP 5
John Coggeshall
 
PPT
Ajax and PHP
John Coggeshall
 
Virtualization for Developers
John Coggeshall
 
ZF2 Modules: Events, Services, and of course, modularity
John Coggeshall
 
PHP Development for Google Glass using Phass
John Coggeshall
 
Virtualization for Developers
John Coggeshall
 
Development with Vagrant
John Coggeshall
 
Introduction to Zend Framework 2
John Coggeshall
 
10 things not to do at a Startup
John Coggeshall
 
Virtualization for Developers
John Coggeshall
 
Building PHP Powered Android Applications
John Coggeshall
 
Ria Applications And PHP
John Coggeshall
 
Beyond the Browser
John Coggeshall
 
Apache Con 2008 Top 10 Mistakes
John Coggeshall
 
Ria Development With Flex And PHP
John Coggeshall
 
Top 10 Scalability Mistakes
John Coggeshall
 
Enterprise PHP: A Case Study
John Coggeshall
 
Building Dynamic Web Applications on i5 with PHP
John Coggeshall
 
PHP Security Basics
John Coggeshall
 
Migrating from PHP 4 to PHP 5
John Coggeshall
 
Ajax and PHP
John Coggeshall
 

Recently uploaded (20)

PPTX
Networking_Essentials_version_3.0_-_Module_3.pptx
ryan622010
 
PDF
The Internet - By the numbers, presented at npNOG 11
APNIC
 
PPTX
西班牙巴利阿里群岛大学电子版毕业证{UIBLetterUIB文凭证书}文凭复刻
Taqyea
 
PPTX
Lec15_Mutability Immutability-converted.pptx
khanjahanzaib1
 
PDF
Cleaning up your RPKI invalids, presented at PacNOG 35
APNIC
 
PPTX
Metaphysics_Presentation_With_Visuals.pptx
erikjohnsales1
 
PDF
Boardroom AI: The Next 10 Moves | Cerebraix Talent Tech
ssuser73bdb11
 
PDF
FutureCon Seattle 2025 Presentation Slides - You Had One Job
Suzanne Aldrich
 
PDF
BRKACI-1001 - Your First 7 Days of ACI.pdf
fcesargonca
 
PDF
Digital burnout toolkit for youth workers and teachers
asociatiastart123
 
DOCX
Custom vs. Off-the-Shelf Banking Software
KristenCarter35
 
PDF
BRKAPP-1102 - Proactive Network and Application Monitoring.pdf
fcesargonca
 
PDF
Enhancing Parental Roles in Protecting Children from Online Sexual Exploitati...
ICT Frame Magazine Pvt. Ltd.
 
PPTX
Softuni - Psychology of entrepreneurship
Kalin Karakehayov
 
PPTX
04 Output 1 Instruments & Tools (3).pptx
GEDYIONGebre
 
PDF
Top 10 Testing Procedures to Ensure Your Magento to Shopify Migration Success...
CartCoders
 
PPTX
Presentation3gsgsgsgsdfgadgsfgfgsfgagsfgsfgzfdgsdgs.pptx
SUB03
 
PPTX
法国巴黎第二大学本科毕业证{Paris 2学费发票Paris 2成绩单}办理方法
Taqyea
 
PDF
BRKSP-2551 - Introduction to Segment Routing.pdf
fcesargonca
 
PPTX
PHIPA-Compliant Web Hosting in Toronto: What Healthcare Providers Must Know
steve198109
 
Networking_Essentials_version_3.0_-_Module_3.pptx
ryan622010
 
The Internet - By the numbers, presented at npNOG 11
APNIC
 
西班牙巴利阿里群岛大学电子版毕业证{UIBLetterUIB文凭证书}文凭复刻
Taqyea
 
Lec15_Mutability Immutability-converted.pptx
khanjahanzaib1
 
Cleaning up your RPKI invalids, presented at PacNOG 35
APNIC
 
Metaphysics_Presentation_With_Visuals.pptx
erikjohnsales1
 
Boardroom AI: The Next 10 Moves | Cerebraix Talent Tech
ssuser73bdb11
 
FutureCon Seattle 2025 Presentation Slides - You Had One Job
Suzanne Aldrich
 
BRKACI-1001 - Your First 7 Days of ACI.pdf
fcesargonca
 
Digital burnout toolkit for youth workers and teachers
asociatiastart123
 
Custom vs. Off-the-Shelf Banking Software
KristenCarter35
 
BRKAPP-1102 - Proactive Network and Application Monitoring.pdf
fcesargonca
 
Enhancing Parental Roles in Protecting Children from Online Sexual Exploitati...
ICT Frame Magazine Pvt. Ltd.
 
Softuni - Psychology of entrepreneurship
Kalin Karakehayov
 
04 Output 1 Instruments & Tools (3).pptx
GEDYIONGebre
 
Top 10 Testing Procedures to Ensure Your Magento to Shopify Migration Success...
CartCoders
 
Presentation3gsgsgsgsdfgadgsfgfgsfgagsfgsfgzfdgsdgs.pptx
SUB03
 
法国巴黎第二大学本科毕业证{Paris 2学费发票Paris 2成绩单}办理方法
Taqyea
 
BRKSP-2551 - Introduction to Segment Routing.pdf
fcesargonca
 
PHIPA-Compliant Web Hosting in Toronto: What Healthcare Providers Must Know
steve198109
 

Migrating to PHP 7

  • 1. Migrating to PHP 7 John Coggeshall – International PHP Conference, 2016 Berlin, Germany @coogle, [email protected]
  • 2. Who’s This Guy? • The Author of ext/tidy • (primary) Author in (almost) 5 books on PHP going from PHP 4 to PHP 7 • Speaking at conferences for a long time !!!!! circa 2004 today
  • 3. Major Concerns when Migrating to PHP 7 • Error Handling • Variable Handling • Control Structure Changes • Removed Features / Changed Functions • Newly Deprecated Behaviors • This talk will not cover every single detail of the changes in PHP 7. That’s what Migration Documentation is for: http://php.net/manual/de/migration70.php
  • 4. Error Handling • One of the biggest breaks you may have to deal with migrating to PHP 7 will be error handling • Especially when using Custom Error Handlers • Many fatal / recoverable errors from PHP 5 have been converted to exceptions • Major Break: The callback for set_exception_handler() is not guaranteed to receive Exception objects
  • 5. Fixing Exception Handlers <?php function my_handler(Exception $e) { /* ... */ } <?php function my_handler(Throwable $e) { /* ... */ } PHP 5 PHP 7
  • 6. Other Internal Exceptions • Some internal class constructors in PHP 5 would create objects in unusable states rather than throw exceptions • In PHP 7 all class constructors throw exceptions • Notably this was a problem in some of the Reflection Classes You should always be prepared to handle an exception thrown from PHP 7 internal classes in the event something goes wrong
  • 7. Parser Errors • In PHP 5, parsing errors (for instance, from an include_once statement) would cause a fatal error • In PHP 7 parser errors throw the new ParseError exception Again, your custom error handlers and exception handlers may need updating to reflect this new behavior
  • 8. E_STRICT is Dead Situation New Behavior Indexing by a Resource E_NOTICE Abstract Static Methods No Error ”Redefining” a constructor No Error Signature mismatch during inheritance E_WARNING Same (compatible) property used in two traits No Error Accessing a static property non-statically E_NOTICE Only variables should be assigned by reference E_NOTICE Only variables should be passed by reference E_NOTICE Calling non-static methods statically E_DEPRECATED
  • 9. Indirect Variables, Properties, Methods • In PHP 5 complex indirect access to variables, properties, etc. was not consistently handled. • PHP 7 addresses these inconsistencies, at the cost of backward compatibility Typically most well-written code will not be affected by this. However, if you have complicated indirect accesses you may hit this.
  • 10. Indirect Variables, Properties, Methods Expression PHP 5 PHP 7 $$foo[‘bar’][‘baz’] ${$foo[‘bar’][‘baz’]} ($$foo)[‘bar’][‘baz’] $foo->$bar[‘baz’] $foo->{$bar[‘baz’]} ($foo->$bar)[‘baz’] $foo->$bar[‘baz’]() $foo->{$bar[‘baz’]}() ($foo->$bar)[‘baz’]() Foo::bar[‘baz’]() Foo::{$bar[‘baz’]}() (Foo::$bar)[‘baz’]() If you are using any of the expression patterns on the left column the code will need to be updated to the middle “PHP 5” column to be interpreted correctly.
  • 11. list() Mayhem • There is a lot of code out there that takes the assignment order of the list() statement for granted: <?php list($x[], $x[]) = [1, 2]; // $x = [2, 1] in PHP 5 // $x = [1, 2] in PHP 7 • This was never a good idea and you should not rely on the order in this fashion.
  • 12. list() Mayhem • Creative use of the list() statement with empty assignments will also now break <?php // Both will now break in PHP 7 list() = $array; list(,$x) = $array;
  • 13. list() Mayhem • Finally, list() can no longer be used to unpack strings. <?php list($a, $b, $c) = “abc”; // $a = “a” in PHP 5, breaks in PHP 7
  • 14. Subtle foreach() changes – Array Pointers • In PHP 5 iterating over an array using foreach() would cause the internal array pointer to move for each iteration <?php $a = [1, 2] foreach($a as &$val) { var_dump(current($a)); } // Output in PHP 5: // int(1) // int(2) // bool(false) <?php $a = [1, 2] foreach($a as &$val) { var_dump(current($a)); } // Output in PHP 7: // int(1) // int(1) // int(1)
  • 15. Subtle foreach() changes – References This subtle change may break code that modifies arrays by reference during an iteration of it <?php $a = [0]; foreach($a as &$val) { var_dump($val); $a[1] = 1; } // Output in PHP 5 // int(0) <?php $a = [0]; foreach($a as &$val) { var_dump($val); $a[1] = 1; } // Output in PHP 7 // int(0) // int(1) In PHP 5 you couldn’t add to an array, even when passing it by reference and iterate over them in the same block
  • 16. Integer handler changes • Invalid Octal literals now throw parser errors instead of being silently ignored • Bitwise shifts of integers by negative numbers now throws an ArithmeticError • Bitwise shifts that are out of range will now always be int(0) rather than being architecture-dependent
  • 17. Division By Zero • In PHP 5 Division by Zero would always cause an E_WARNING and evaluate to int(0), including attempting to do a modulus (%) by zero • In PHP 7 • X / 0 == float(INF) • 0 / 0 == float(NaN) • Attempting to do a modulus of zero now causes a DivisionByZeroError exception to be thrown
  • 18. Hexadecimals and Strings • In PHP 5 strings that evaluated to hexadecimal values could be cast to numeric values • I.e. (int)“0x123” == 291 • In PHP 7 strings are no longer directly interpretable as numeric values • I.e. (int)”0x123” == 0 • If you need to convert a string hexadecimal value to its integer equivalent you can use filter_var() with the FILTER_VALIDATE_INT and FILTER_FLAG_ALLOW_HEX options to convert it to an integer value.
  • 19. Calls from Incompatible Contexts • Static calls made to a non-static method with an incompatible context (i.e. calling a non-static method statically in a completely unrelated class) has thrown a E_DEPRECATED error since 5.6 • I.e. Class A calls a non-static method in Class B statically • In PHP 5, $this would still be defined pointing to class A • In PHP 7, $this is no longer defined
  • 20. yield is now right associative • In PHP 5 the yield construct no longer requires parentheses and has been changed to a right associative operator <?php // PHP 5 echo yield -1; // (yield) – 1; yield $foo or die // yield ($foo or die) <?php // PHP 7 echo yield -1; // yield (-1) yield $foo or die // (yield $foo) or die;
  • 21. Misc Incompatibilities • There are a number of other (smaller) incompatibilities between PHP 5 and PHP 7 worth mentioning • ASP-style tags <% %> have been removed • <script language=“php”> style tags have been removed • Assigning the result of the new statement by reference is now fatal error • Functions that have multiple parameters with the same name is now a compile error • switch statements with multiple default blocks is now a compile error • $HTTP_RAW_POST_DATA has been removed in favor of php://input • # comments in .ini files parsed by PHP are no longer supported (use semicolon) • Custom session handlers that return false result in fatal errors now
  • 22. Removed Functions • Numerous functions have been removed in PHP 7 and replaced with better equivalents where appropriate Variable Functions call_user_method() call_user_method_array() Mcrypt mcrypt_generic_end() mcrypt_ecb() mcrypt_cbc() mcrypt_cfb() mcrypt_ofb() Intl datefmt_set_timezone_id() IntlDateFormatter::setTimeZoneId() System set_magic_quotes_runtime() magic_quotes_runtime() set_socket_blocking() dl() (in PHP-FPM) = GD imagepsbbox() imagepsencodefont() imagepsextendfont() imagepsfreefont() imagepsloadfont() imagepsslantfont() imagepstext() • Removed Extensions: ereg, mssql, mysql, sybase_ct
  • 23. Removed Server APIs (SAPIs) and extensions • Numerous Server APIs (SAPIs) have been removed from PHP 7: • aolserver • apache • apache_hooks • apache2filter • caudium • continunity • isapi • milter • nsapi • phttpd • pi3web • roxen • thttpd • tux • webjames
  • 24. Deprecated Features • A number of things have been deprecated in PHP 7, which means they will now throw E_DEPRECATED errors if you happen to be using them in your code • PHP 4 style constructors • Static calls to non-static methods • Passing your own salt to the password_hash() function • capture_session_meta SSL context option • For now these errors can be suppressed (using the @ operator) but the code should be updated as necessary.
  • 25. Changes to Core Functions • When migrating from PHP 5 to PHP 7 there are a few functions that have changed behaviors worth noting • mktime() and gmmktime() no longer accept the $is_dst parameter • preg_replace() no longer supports the /e modifier and preg_replace_callback() must now be used • setlocale() no longer accepts strings for the $category parameter. The LC_* constants must be used • substr() now returns an empty string if then $string parameter is as long as the $start parameter value.
  • 26. Name Conflicts • There are a lot of new things in PHP 7 that didn’t exist in PHP 5 • New Functions • New Methods • New Classes • New Constants • New Exceptions • You should review the PHP Migration documentation for what’s been added to determine if any code you’ve written now conflicts with something internal to PHP 7 • For example, do you have an IntlChar class in your application?