PHP 7 has been finally released!!! You can download the source code here: php-7.0.0. We describe how to install PHP 7 here: Installing PHP 7.
Lack of a native Unicode support was one of the biggest PHP drawbacks. In 2005, developers decided to change this. The newly formed project was designed to provide a native Unicode support to PHP. To achieve this goal, developers decided to use the ICU library (International Components for Unicode). Another significant feature of the project was representing UTF-16 text strings. It was planned to release the project as version 6.0, but we can see only PHP 5.3 and PHP 5.4, both without Unicode integration. As of 2015, there is an ongoing work on a new major version of PHP – PHP 7. The PHP 6 with its unicode experiment had never been released, so the name was abandoned.
PHP 7.0.0 has been finally released, and you can already check the official PHP 7 repo and download the source code here: php-7.0.0.
PHP 7.0.0 marks the start of the new major PHP series, which introduces the following features:
new Zend Engine
better performance
optimized memory usage
consistent support for 64-bit
AST (Abstract Syntax Tree)
revamped Exception hierarchy with fatal errors converted to Exceptions
null coalescing operator
secure generator of random numbers
declarations for both Return and Scalar types
removed unnecessary extensions and SAPIs
Anonymous Classes
You can download the source of PHP 7.0.0 from the official PHP website: downloads page. If you are looking for Windows binaries, they are here: PHP 7 Windows binaries. To examine all new changes introduced in PHP 7, check the ChangeLog. Another important aspect is migration to PHP 7. You can find the appropriate guide here: PHP 7 migration guide.
PHP 7 RC 8 has been released
PHP 7 RC 8 has been released, and it includes 11 bug fixes. If no major problems appear, PHP 7.0.0 GA will be available on December 3rd!
PHP 7 Docker Image for Magento 2
magento2-php – image that contains PHP configurations for Magento 2. These versions are available:
This feature allows you to extend the “FileSystem” with logic that is quite difficult to perform in other languages. For instance, the MS-Excel Stream handler provides the ability to create a MS Excel file as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
$fp=fopen("xlsfile://tmp/test.xls","wb");
if(!is_resource($fp)){
die("Cannot open excel file");
}
$data=array(
array("Name"=>"Bob Loblaw","Age"=>50),
array("Name"=>"Popo Jijo","Age"=>75),
array("Name"=>"Tiny Tim","Age"=>90)
);
fwrite($fp,serialize($data));
fclose($fp);
Magic Methods
These are fall-through methods that can be called every time you invoke a method that doesn’t exist as well as assign or read the same property among other things.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
interfaceAllMagicMethods{
// accessing undefined or invisible (e.g. private) properties
publicfunction__get($fieldName);
publicfunction__set($fieldName,$value);
publicfunction__isset($fieldName);
publicfunction__unset($fieldName);
// calling undefined or invisible (e.g. private) methods
publicfunction__call($funcName,$args);
publicstaticfunction__callStatic($funcName,$args);// as of PHP 5.3
// on serialize() / unserialize()
publicfunction__sleep();
publicfunction__wakeup();
// conversion to string (e.g. with (string) $obj, echo $obj, strlen($obj), ...)
publicfunction__toString();
// calling the object like a function (e.g. $obj($arg, $arg2))
publicfunction__invoke($arguments,$...);
// called on var_export()
publicstaticfunction__set_state($array);
}
Standard Class as a Neat Container
Now, using an array for holding several attributes can be replace with a standard class, which is particularly helpful in a string while accessing these variables:
1
$string=$person['name'].' is '.$person['age'].' years old.';
vs
1
$string="$person->name is $person->age years old.";
Return Value of Include Files
Now, include files have a return value. And it is possible to assign it to a variable.
1
2
3
4
5
6
7
8
9
10
11
12
13
// config.php
returnarray(
'db'=>array(
'host'=>'example.org',
'user'=>'usr',
// ...
),
// ...
);
// index.php
$config=include'config.php';
echo$config['db']['host'];// example.org
‘or’ operator has lower precedence than ‘=’
And you can take advantage out of this feature:
1
2
$page=(int)@$_GET['page']
or$page=1;
In a situation when the value of the first assignment evaluates to true, the second one will be ignored.
Variable variables and functions
This concept applies to object parameters as well ($some_object->$some_variable);
1
2
3
4
5
6
7
8
9
10
11
12
13
$foo='bar';
$bar='foobar';
echo$$foo;//This outputs foobar
functionbar(){
echo'Hello world!';
}
functionfoobar(){
echo'What a wonderful world!';
}
$foo();//This outputs Hello world!
$$foo();//This outputs What a wonderful world!
Functions with an undefined number of arguments
In PHP 7, func_get_args() provides the ability to use functions with an undefined number of arguments:
Rogue Wave Software has announced the acquisition of Zend, so now the company will get accelerated abilities for reaching even the largest enterprises with the goal to help them accelerate innovations. As a result, the most popular programming language of the Web will get even wider distribution (the portfolio of Rogue Wave already includes more than 3,000 enterprise customers). In its turn Rogue Wave will be able to expand into the Web & Mobile space.
The acquisition leads both PHP 7 and Zend Framework 3 to a new level of quality.
PhpStorm 9
PhpStomp 9 supports PHP 7. The best PHP IDE now offers refined editing and debugging options, better code understanding, significant boost in productivity, and a total support for remote development. Other PHP features are:
Improved structure view
PHP surrounds in both HTML in PHP files
Brackets, parentheses, and braces now support colour settings
If you are looking for some practical exercises to master PHP 7, there is a good way to improve your current skills. On php7-tutorial.com, you will discover all new changes and features related to the upcoming version of the new language. The tutorial includes a lot of simple exercises based on solving problems or fixing bugs. It is also necessary to mention that all steps are corresponded to RFC and have explanations. Besides, the website illustrates PHP 7 timeline:
Backwards compatibility issues
Unfortunately some new improvements introduced in PHP 7 could potentially break a legacy app running on previous versions of the language. Below, we discuss this problem and illustrate several examples.
Deprecated Items Removed
As we’ve mentioned before, a number of deprecated items have been removed from PHP 7. Thus, the language evolution takes place, but there are still some legacy applications that rely on these deprecated items. You can see a list of everything that has been removed below.
Uniform Variable Syntax
A series of inconsistencies takes place in case of evaluating variable-variable expressions. Luckily, you can fix these problems with the aid of the uniform variable syntax. Let’s see, how the same $person->$property[‘first’]is evaluated in PHP 5 and PHP 7.
In case of PHP 5, the expression is evaluated as $person->{$property[‘first’]} and interpreted as $person->name. This example illustrates a clear inconsistency with the left to right evaluation order.
In case of PHP 7, the same expression is evaluated as {$person->$property}[‘first’]. Thus, the interpreter will evaluate $person->$property first. As a result the code example will be irrelevant for PHP 7 since $property is an array; consequently, it is impossible to convert it to a string.
Luckily, you can easily fix the problem by using curly braces: explicitly define the evaluation order as follows: $person->{$property[‘first’]}. This action leads to the same behavior on PHP 5 and PHP 7. Please note that the implementation of left-to-right variable syntax is a reason why many previously invalid expressions will now work.
Multiple “default” clauses
Multiple default clauses in a switch cause a Fatal Error in PHP 7. As for PHP 5, the last default is used, while in the new version require using one default clause in switch statements.
For further information about other backwards compatibility issues as well as a detailed description of new features, follow this link.
PHP 7 screencasts
Laracasts.com offers 7 amazing PHP screencasts for free. You can choose between Some Vagrant, Some PHP 7; Scalar Typehints; Return Type Declarations; Spaceships; The Null Coalesce Operator; Grouped Imports; and Anonymous Classes.
As for a new PHP 7 overview, it has been published on Zend Developer Zone. The author once again summarizes all features and improvements of the new PHP version.
WordPress is gradually changing its core for the upcoming PHP 7. According to new benchmarks WordPress on PHP 7 shows a 2-3x increase in speed compared to PHP 5.6.
PHP 7 nightlies have become the part of the automated test matrix; every commit against the new PHP version has been tested; and a lot of issues have been fixed. Besides, as many plugins and themes as possible are ready for PHP 7. As for Uniform Variable Syntax, WordPress is absolutely optimized for it.
As you can see, the platform is going to be ready to fully support PHP 7 right after its official release (November 12, 2015). At the same time, WordPress will continue to support older PHP versions.
New Types of PHP 7
We’ve already mentioned about new types of PHP 7. Below, you can find a short overview of return and scalar types.
Return types
The type system of PHP 7 has been enhanced with return types. Therefore, functions and methods are able to specify the type of value they explicitly return. Here is the example:
$a=newAddress('123 Main St.','Chicago','IL','60614');
$e=newEmployee($a);
print$e->getAddress()->getStreet().PHP_EOL;
// Prints 123 Main St.
Check this post for a more detailed description of return types.
Scalar types
Return types are just the beginning, as PHP 7 goes even further introducing scalar types.
Since the new version of the language adds the ability to type against scalar values, you get new opportunities for working with string, int, or other type.
Scalar types provide greater clarity within the language. Besides, they introduce the ability to catch more bugs at early stages of development. As a result, it is possible to create more reliable code.
Four new types specified for return values are int, float, bool, and string. Just check the following example:
For further explanations, check this PHP 7 guide. We think that it is not necessary to repeat such a good material.
Threading for PHP
There is a good project on GitHub that introduces multi-threading compatible with PHP based on Posix Threads. It offers the following features:
Usability. This OO Threading API for PHP 7 is easy to use and quick to learn.
Wide opportunities. With the help of this project, you will be able to execute any, all predefined and user declared methods and functions. The project also supports closures.
Synchronization. Threading for PHP includes ready made synchronization out-of-the-box.
SAPI environments. The project offers seamless operation in multi-threaded SAPI environments.
php7cc is a PHP 7 compatibility checker. Being a CLI tool, the project is designed to simplify your migration from PHP 5.3-5.6 to PHP 7. php7cc scans existing code for potentially troublesome statements and generates reports with data related to filenames and line numbers. Besides, the tools offers short problem descriptions. Please note that php7cc does not fix code automatically. Check the project on GitHub for further information.
PHP 7.0.0 RC2 has been released. Being the seventh pre-release of the final release, RC2 still remains a development preview, so all PHP coders are encouraged to test this version for reporting bugs. If you are going to make PHP 7 better use this link: the PHP bug tracking system. Please note that PHP 7.0.0 RC2 is not for production. As for bug fixes, it contains 28 improvements, as well as 250+ commits.
PHP 7.0.0 RC3 will be available on the 17th of September. This is the official Timetable:
PHP 7 Timetable
As you can see, the final version of PHP 7 will be available on the 12th of November.
Although PHP 7 RC2 has just been released, there are already some benchmarks related to the new version. For instance, Michael Larabel has been testing it across a range of Linux systems. He states that PHP 7 has phenomenal speed and is really about twice as fast as PHP 5.6. Michael performed some benchmarks on Ubuntu Linux x86_64 comparing the RC2 performance to PHP 5.3/5.4/5.5/5.6. You can check the results of his work here: PHP 7.0 Is Showing Very Promising Performance Over PHP 5, Closing Gap With HHVM.
PHP 7.0.0 RC 1
PHP 7.0.0 RC 1 is now available! Being the sixth pre-release version of PHP 7, it is available for testing. Bug reports are highly anticipated, so you can use this bug tracking system to provide developers with information about any problems.
Since PHP 7.0.0 RC 1 is a development preview, you shouldn’t use it in production. The new version already contains 27 bug fixes and over 200 stability improvements related to database, assert, streams, array,etc.
Due to a new version of Zend Engine, PHP 7.0.0 offers the following features:
Better performance: it is is up to 2 times faster than PHP 5.6;
64-bit support;
Fatal errors are now Exceptions (but not all of them);
Old SAPIs and extensions have been removed;
Return Type Declarations;
Scalar Type Declarations;
The null coalescing Operator (??);
Combined comparison Operator (<=>);
Anonymous Classes.
For more information about new features introduced in PHP 7.0.0 RC 1 , you can look here. For source downloads check this page. Windows source and binaries are here.
Please note that RC 2 will be released on the 3rd of September.
Deprecated functionality which will be removed in PHP 7
Deprecated extensions are ext/ereg and ext/mysql. You can use ext/pcre instead of the first one, and ext/mysqli or ext/pdo_mysql instead of the second one.
Deprecated language features are ‘assignment of new by reference’ (use normal assignment) and ‘non-static methods scoped calls from incompatible $this context’.
Deprecated ini options include xsl.security_prefs (use XsltProcessor::setSecurityPrefs as a replacement) and iconv.input_encoding, iconv.output_encoding, iconv.internal_encoding, mbstring.http_input,mbstring.http_output, and mbstring.internal_encoding (php.input_encoding, php.internal_encoding and php.output_encoding as a replacement).
Deprecated functions:
dl on fpm-fcgi
set_magic_quotes_runtime and magic_quotes_runtime
set_socket_blocking (stream_set_blocking as a replacement)
mcrypt_generic_end (mcrypt_generic_deinit as a replacement)
mcrypt_ecb, mcrypt_cbc, mcrypt_cfb and mcrypt_ofb (mcrypt_encrypt and mcrypt_decrypt as a replacement)
datefmt_set_timezone_id and IntlDateFormatter::setTimeZoneID (datefmt_set_timezone and IntlDateFormatter::setTimeZone as a replacement)
Deprecated miscellaneous functionality:
The $is_dst parameter used with the gmmktime() and mktime() functions
# style comments from ini files (use ; style comments as a replacement)
setlocale() string category names (LC_* constants as a replacement)
Unsafe curl file uploads (CurlFile as a replacement)
preg_replace() eval modifier (preg_replace_callback as a replacement)
such driver option as PDO::PGSQL_ATTR_DISABLE_NATIVE_PREPARED_STATEMENT (since PHP 5.6; use PDO::ATTR_EMULATE_PREPARES as a replacement)
such context options as CN_match and SNI_server_name stream (peer_name as a replacement)
You can see the following list of deprecated PHP 7 functions here.
PHP 7 on Magento EE
Need more information about PHP 7? Check it below! The new version will be lightning fast, as the recent benchmark shows.
Magento EE 1.14.2.1 with disabled caches was tested with PHP-FPM 5.5, HHVM, and PHP-FPM 7.0 Beta3. You can see the results of the benchmark below. I can only add, that heavy Magento EE has demonstrated some unbelievable results with PHP-FPM 7.0. Thus, PHP 7 is going to meet all expectations.
Interview with Dmitry Stogov
Below, you will find some core aspects of an interview with Dmitry Stogov – Chief Performance Engineer at Zend Technologies and the PHP 7 lead developer.
Dmitry told that the decision to turn PHPNG into a core of PHP 7 was taken in August 2014. Almost after a year, we can talk about the following features:
An enhanced performance;
Low entry barriers;
An ability to define function values as well as argument types;
Multiple error fixes (some errors can be handled by the app);
Assert() function for debugging (it is also possible to turn it off on production);
64-bit integration;
ext/mysql and ext/ereg are no longer exist in the main tree;
Unfortunately, PHP 7 was frozen in the beginning of 2015, but the release is still planned for the second half of the year. At the same time, PHPNG roadmap is over.
Now we know that PHP 7 will be released in November 2015 (check the official PHP Wiki)! The new version includes a lot of changes and improvements. Below, you will find all of them.
Better Performance
Every PHP coder is waiting for the performance improvement of PHP 7. The new version of coding language offers the incredibly new performance when it comes to applications. PHP 7 is better, faster and more powerful due to the refactored Zend Engine. First of all it uses more compact data structures. The second reason of the new improved performance is related to less heap allocations/deallocations. But how does this affect applications IRL?
Real world apps will receive a near 100% performance boost, as well as reduced memory consumption. Please note, that is only the average value, so different applications will not show the same results.
It is also necessary to mention, that PHP 7 offers new opportunities when it comes to optimisations. Due to refactored codebase future PHP versions will show even better performance. Check the following links to see how the performance has been changed compared to other versions of PHP: Comparisons by Zend; Comparisons by talks.php.net.
PHP 7 Performance by Zend
New Features
Below you will find the detailed descriptions of PHP 7 features.
Combined Comparison Operator
The Combined Comparison Operator which is also known as Spaceship Operator illustrates the new abilities related to the performing of 3-way comparisons from 2 operands. The possible integer return values:
a positive integer – the left-hand operand > the right-hand one;
a negative integer – right-hand operand > left-hand one;
0 – both are equal.
The precedence is the same as in a case of equality operators – ==, !=, ===, !==. It is also necessary to mention that the behaviour repeats the behaviour of other loose comparison operators – <, >=, etc. Moreover, it is non-associative, that’s why it is forbidden to chain the operands, like 1 <=> 2 <=> 3.
PHP
1
2
3
4
5
6
7
8
// compares strings lexically
var_dump('PHP'<=>'Node');// int(1)
// compares numbers by size
var_dump(123<=>456);// int(-1)
// compares corresponding array elements with one-another
var_dump(['a','b']<=>['a','b']);// int(0)
Please note that using objects as operands (with this operator) results in undefined behaviour, since they are not comparable.
You can read more about Combined Comparison Operator here.
Isset Ternary Operator
The isset ternary or null coalesce operator shows another important improvement represented in PHP 7. The new feature is related to the ternary operator. It plays a role of a shorthand notation used for more convenient performing of isset() checks. The new syntax was developed, since the aforementioned process is widespread in applications
There two flavours of scalar type declarations in PHP 7. They are coercive (default) and strict. Not that integers (int), floating-point numbers (float), strings (string), and booleans (bool) can be enforced either strictly or coercively. They augment class names, array, interfaces, and callable introduced in the PHP 5.x.
PHP
1
2
3
4
5
6
7
// Coercive mode
functionsumOfInts(int...$ints)
{
returnarray_sum($ints);
}
var_dump(sumOfInts(2,'3',4.1));// int(9)
A single declare() directive enables a strict mode. It should be placed at the top of the file. Thus, you will be able to configure the strictness of typing for scalars on a per-file basis. In addition to the type declarations of parameters, this directive affects a function’s return type (check ReturnTypeDeclarations for the additional information), as well as built-in PHP functions, and functions related to loaded extensions.
If an E_RECOVERABLE_ERROR is produced, it means that the type-check fails. As for the leniency, the only one represented in a strict typing is the automatic conversion of integers to floats. Keep in mint, that it is related to a one way process but not vice-versa. An integer must be provided in a float context.
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
declare(strict_types=1);
functionmultiply(float$x,float$y)
{
return$x*$y;
}
functionadd(int$x,int$y)
{
return$x+$y;
}
var_dump(multiply(2,3.5));// float(7)
var_dump(add('2',3));// Fatal error: Argument 1 passed to add() must be of the type integer, string given...
Type-checking. When this process is performed the only context that applies is the invocation context. The strict typing does not apply to the function/method definitions. It applies to function/method calls only. Let’s explain the above example. It includes two functions which can be declared in either a strict or coercive file. In the example, they are called in a strict file, so the applied typing rules are strict typing rules.
Binary compatibility break: classes with the following names are forbidden: int, string, float, and bool.
With the help of return type declarations you specify the return type related to method, function, or closure. PHP 7 supports the following return types: string, float, int, bool, callable, array, self (limited to methods only), parent (also limited methods only), Closure, the class name, and the interface name.
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
functionarraysSum(array...$arrays):array
{
returnarray_map(function(array$array):int{
returnarray_sum($array);
},$arrays);
}
print_r(arraysSum([1,2,3],[4,5,6],[7,8,9]));
/* Output
Array
(
[0] => 6
[1] => 15
[2] => 24
)
*/
Subtyping play an important role here. Since return types rely on invariance, an implemented in a contract as defined or overridden in a subtyped class method must have the return type which matches the method it is reimplementing or implementing.
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classA{}
classBextendsA{}
classC
{
publicfunctiontest():A
{
returnnewA;
}
}
classDextendsC
{
// overriding method C::test() : A
publicfunctiontest():B// Fatal error due to variance mismatch
{
returnnewB;
}
}
If you see an E_COMPILE_ERROR caused by overriding method D::test() : B it means that covariance is not allowed. To fix the problem, you must check if D::test() method has a return type of A.
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classA{}
interfaceSomeInterface
{
publicfunctiontest():A;
}
classBimplementsSomeInterface
{
publicfunctiontest():A// all good!
{
returnnull;// not good!
}
}
In the aforementioned example, the reason of E_RECOVERABLE_ERROR is null since it isn’t a valid return type. Please note, that the only instance that can be returned is the one of the class A.
["Command line code0x104c5b612":"class@anonymous":private]=>
int(10)
}
*/
Note that in the situation when you are nesting an anonymous class within another class, the first one does not get any access to protected or private methods / properties of the second. In order to get them, the anonymous class can extend the outer class. Thus, properties of the outer class in the anonymous class should be passed through it’s constructor:
This new feature provides the ability to output a UTF-8 encoded unicode codepoint in a heredoc or a double-quoted string. It is also necessary to mention that any valid codepoint is accepted, with optional leading 0’s.
PHP
1
2
3
echo"\u{aa}";// ª
echo"\u{0000aa}";// ª (same as before but with optional leading 0's)
Want to invoke a closure while binding an object scope to it? PHP 7 provides suh opportunity with the new call() method for closures. As a result, you get a more performant and compact code, since the the need of creating an intermediate closure before invoking it is removed.
This feature adds new level of security to PHP 7. It is designed for unserializing objects and untrusted data. With its help developers can prevent code injections by whitelisting classes that can be unserialized.
PHP
1
2
3
4
5
6
7
8
// converts all objects into __PHP_Incomplete_Class object
The new IntlChar class is used to define a quantity of static methods and constants utilized for manipulating unicode characters. It seeks to expose the additional functionality of ICU.
PHP
1
2
3
printf('%x',IntlChar::CODEPOINT_MAX);// 10ffff
echoIntlChar::charName('@');// COMMERCIAL AT
var_dump(IntlChar::ispunct('!'));// bool(true)
IntlChar class requirements: the Intl extension must be installed.
Binary compatibility break: don’t call this class IntlChar in the global namespace.
There is an older assert() function in PHP, and expectations form a backwards compatible enhancement to it. With the help of this new feature, the following is possible: zero-cost assertions in production code; throwing of custom exceptions on error.
The example of assert() function’s prototype:
PHP
1
voidassert(mixed$expression[,mixed$message]);
$expression is evaluated if it is a string. In a case when the first argument is falsy, we get the failed assertion. There are 2 possible variants with the second argument. First of all it can be a plain string causing an AssertionException. The second use case is role of a custom exception object which contains an error message.
The two new PHP.ini settings, which comes with this feature are: “zend.assertions = 1” and “assert.exception = 0”
zend.assertions values:
1 = it generates and executes code in a development mode;
0 = it also generates a code, but this time jumping around at it at a runtime;
-1 = the code is not generated (zero-cost / production mode)
With the assert.exception an exception is thrown only in a case when an assertion fails. In order to stay compatible with the old assert() function, this feature is switched off.
With this new feature of PHP 7, it is possible to group multiple use declarations on a basis of the parent namespace. It is very convenient for importing multiple classes with the same namespace.
The generator functionality has been introduced in PHP 5.5. Now it is used as a basis for the implementation of Generator Return Expressions feature, which provides a return statement with the ability to be used within a generator where a final expression is returned. Please note, that the return by reference is prohibited. The value can be fetched with the help the following method: Generator::getReturn(). The last one can be used with the generator with finishing yielding values.
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// IIFE syntax now possible - see the Uniform Variable Syntax subsection in the Changes section
$gen=(function(){
yield1;
yield2;
return3;
})();
foreach($genas$val){
echo$val,PHP_EOL;
}
echo$gen->getReturn(),PHP_EOL;
// output:
// 1
// 2
// 3
The ability to return the final value from a generator explicitly simplifies the previous algorithm a lot. With this new feature, the final value can be returned by a generator, which can be executed by the client code.
Generator delegation is about returning expressions from generators by using a new yield from <expr> syntax , where any Traversable object or array are possible. It is advanced as last as no longer valid, and then the calling generator is used for the continuation of the execution. With this feature yield statements are divided into smaller operations. As a result, we get a cleaner reusable code.
With this feature, it is possible to pass in an options array to the session_start() function. The following is used in order to arrange session-based php.ini options:
PHP
1
session_start(['cache_limiter'=>'private']);// sets the session.cache_limiter option to private
session.lazy_write is a new php.ini setting introduced by this feature. It is set to true by default so the session data is rewritten only in a case if it changes.
This new feature provides more clear code for the preg_replace_callback() function. Callbacks are registered on a per-regular expression basis; an associative array is used with the callback as a value and the regular expression as the key.
Since constant, property, and method names are allowed within interfaces, classes, and traits, the surface of BC breaks for new keywords is now reduced, as well as is is possible to avoids naming restrictions on APIs now.
The following is useful for creating internal DSLs with fluent interfaces:
PHP
1
2
// 'new', 'private', and 'for' were previously unusable
With this new change introduced in PHP 7, variable operators get much wider orthogonality. The number of new operator combinations is now possible. In previous PHP versions this combinations were prohibited. The new ways of achieving old operations in terser code are also available.
PHP
1
2
3
4
5
6
7
8
9
10
11
// nesting ::
$foo::$bar::$baz// access the property $baz of the $foo::$bar property
// nesting ()
foo()()// invoke the return of foo()
// operators on expressions enclosed in ()
(function(){})()// IIFE syntax from JS
// operator support on dereferencable scalars
'string'->toUpper();// call the toUpper() method on the string 'string'
Now it is possible to combine variable operators arbitrarily. This ability comes from the semantics evaluation reversing related to indirect variable, property, and method references. The new behaviour introduced in PHP 7 is much more intuitive, as it follows a left-to-right order:
Thanks for the new exceptions in the engine, many fatal and recoverable fatal errors are converted into exceptions. As a result, apps graceful degradation is possible through custom procedures of error handling. Another subsequence is the inability for cleanup-driven features to be executed. In a case of using exceptions for app errors, stack traces are produced for the additional information on debugging.
PHP
1
2
3
4
5
6
7
8
9
10
functionsum(float...$numbers):float
{
returnarray_sum($numbers);
}
try{
$total=sum(3,4,null);
}catch(TypeError$typeErr){
// handle type error here
}
The new hierarchy:
PHP
1
2
3
4
5
6
7
interfaceThrowable
|-Exception implementsThrowable
|-...
|-Error implementsThrowable
|-TypeError extendsError
|-ParseError extendsError
|-AssertionError extendsError
Binary compatibility break:
Since exceptions are thrown, custom error handlers utilized for handling recoverable fatal errors are not working.
Parse errors which occur in eval() -ed code are now exceptions, they should be wrapped in a try…catch block
This change has an influence on PHP’s exception hierarchy. The new exception hierarchy:
PHP
1
2
3
4
5
6
7
interfaceThrowable
|-Exception implementsThrowable
|-...
|-Error implementsThrowable
|-TypeError extendsError
|-ParseError extendsError
|-AssertionError extendsError
It is necessary to mention that the Throwable interface is implemented by such base class hierarchies as Exception and Error. It defines the below contract:
PHP
1
2
3
4
5
6
7
finalpublicstringgetMessage(void)
finalpublicmixed getCode(void)
finalpublicstringgetFile(void)
finalpublicintgetLine(void)
finalpublicarraygetTrace(void)
finalpublicstringgetTraceAsString(void)
publicstring__toString(void)
Note that it is impossible to implement Throwable by user-defined classes. You should use a custom exception class which extends one of the pre-existing exceptions classes in PHP.
Another important change introduced in PHP 7 is related to ZPP Failure on Overflow. You can find it’s detailed description here.
Fixes to foreach()’s Behaviour
The new change eliminates the undefined behaviour of edge-cases making semantics more intuitive:
foreach() by value on arrays
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$array=[1,2,3];
$array2=&$array;
foreach($arrayas$val){
unset($array[1]);// modify array being iterated over
echo"{$val} - ",current($array),PHP_EOL;
}
// Pre PHP 7 result
1-3
3-
// PHP 7+ result
1-1
2-1
3-1
In a case of using by-value semantics, the array being iterated over isn’t modified in-place. The defined behaviour is also typical for current(), since it begins at the start of the array.
foreach() by reference on objects and arrays; by value on objects
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$array=[1,2,3];
foreach($arrayas&$val){
echo"{$val} - ",current($array),PHP_EOL;
}
// Pre PHP 7 result
1-2
2-3
3-
// PHP 7+ result
1-1
2-1
3-1
Note that the current() function is not affected by iteration of foreach() on the array anymore. Also, nested foreach()s which rely on by-reference semantics now work independently:
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$array=[1,2,3];
foreach($arrayas&$val){
echo$val,PHP_EOL;
foreach($arrayas&$val2){
unset($array[1]);
echo$val,PHP_EOL;
}
}
// Pre PHP 7 result
1
1
1
// PHP 7+ result
1
1
1
3
3
3
Binary compatibility break: reliances on old semantics don’t work.
The list() function doesn’t support strings, but there were a few exceptions:
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// array dereferencing
$str[0]='ab';
list($a,$b)=$str[0];
echo$a;// a
echo$b;// b
// object dereferencing
$obj=newStdClass();
$obj->prop='ab';
list($a,$b)=$obj->prop;
echo$a;// a
echo$b;// b
// function return
functionfunc()
{
return'ab';
}
list($a,$b)=func();
var_dump($a,$b);
echo$a;// a
echo$b;// b
Now string usage with list() is forbidden in all cases.
Moreover, empty list()‘s now cause a fatal error. Another important thing that has been changed is the order of assigning variables (changed to left-to-right):
PHP
1
2
3
4
5
6
7
8
9
10
11
$a=[1,2];
list($a,$b)=$a;
// OLD: $a = 1, $b = 2
// NEW: $a = 1, $b = null + "Undefined index 1"
$b=[1,2];
list($a,$b)=$b;
// OLD: $a = null + "Undefined index 0", $b = 2
// NEW: $a = 1, $b = 2
Binary compatibility break:
It is impossible to make list() equal to any non-direct string value. null is now be the value for both $a and $b variable (see the examples above).
Invoking list() with no variables causes a fatal error.
It is also impossible to make reliance upon the old right-to-left assignment order, since it will not work in PHP 7.
We are looking forward to seeing the future release of PHP 7. Since it is an important event for the whole coding world, the great future impact is inevitable. And don’t confuse PHP 7 with PHP 6 – the last one seems dead forever. More news coming soon.
We still do not know all the features of PHP 7, but some of them are already implemented, so we can talk about them as a part of new major PHP version. First of all we are waiting for the significant performance improvement. With version 7 PHP should receive a JIT engine, which can dynamically compile Zend opcodes into a native machine code. As a result the code will run noticeably faster next time it is used. Chances are, that Abstract Syntax Tree would be implemented as an intermediary step for the PHP 7 compilation process. There is also a high possibility for Asynchronous programming. This would allow PHP 7 and its future versions to implement the execution of parallel tasks caused by the same request. As a result we will see a better performance.
The development of PHP 7 should last between 1 and 3 years. According to the previous information, there were no official plans for the final PHP 7 release date, but it could be some time in 2016. Chances were, we would see an early alpha in 2015, but the situation had been changed:
How to install and where to try PHP 7
PHP 7 on Ubuntu 14.04
Enrico Zimuel tells how to install PHP 7 on Ubuntu 14.04. He uses PHP 7.0.0-dev, which is based on PHPNG. The author tells about errors. The post is very useful, if you are going to use the same environment.
There is also a docker container with nightly build of PHP 7. It provides you with the ability to run unit tests with a 1 line setup. In addition, you will be able to try out new features of PHP 7.
PHP 7 Development Box is a repository, that houses configuration scripts required for building a CentOS 7 based box, which will be suitable for extension development and testing with PHP 7. In addition, you will get a Vagrantfile.
Expected features of PHP 7 include enhanced performance, JIT Engine, Standalone Multi-threaded build in a web server, Abstract Syntax Tree, and Asynchronous I/O layer refactoring. More information about them, you can read at phpzag.
New performance
There is also a post at magento2x. The author also tells about the most probable features and a possible release date. You can find the full article here.
The post at PHP7.ca is more informative. To the aforementioned features, the author adds the expanded use of operators (->, (), [], {}, ::). He also makes a strong emphasis on reasons why we should skip to PHP 7.
The new operator
Along performance improvements, PHP 7 will provide deprecation of some existing features. Some old functionality is not useful anymore, thus ext/ereg and ext.mysql have all chances to be replaced by other extensions. The deprecation list also includes string category names in setlocale() and # style comments in ini files. In their turn, the phpng improvements in version 7 are focused on memory allocation and hash tables. Last year results of PHPNG show a 35 % improvements on synthetic tests and 20-70 % speedup on real apps (60% for a WordPress home page). The results of PHP 7 should be higher. The new technology provides a support for most PHP extensions. It also provides speed results, which are comparable to the HHVM 3.3.0. Hit this link to read the full article.
Return Type Declarations
And don’t forget to check article at sitepoint.com. The author tells about PHP 7 Revolution. He starts with a comparison of PHP 5.7 and PHP 7. Then he tells about return types – PHP 7 is finally getting them. The author also makes an emphases on removing artifacts, as the upcoming version of PHP proposes to eliminate PHP4 style constructors. In addition, he tells about extension API changes. Beware! Changes in PHP 7 can cause a delay with extension porting to the new version. You can find the full article here.
The post at thephp.cc is about PHP 7 re-engineering. The author tells how this process will affect the PHP projects. For example, the new changes have all chances to break Magento 1 on PHP 7. Additionally, he tells about the PEAR environment, which stopped working with PHP 7, and the consequences of this novation.
You can also check episode 57 of the Lately in PHP podcast. Its about features and extensions to be removed, the opcode cache extension, the access of API to parsed PHP code abstract syntax tree, the Zend Open Source JIT engine, etc. The duration of the podcast is 55 minutes.
This article at phpclasses teaches how to write PHP 7 Unit tests by using strict type hinting. The author uses the example from his practice. He also provides link to his php7 strict types testing repo.
Our Expectations
Below, you will find our expectations for PHP 7. The material is based on two articles: this one and it’s continuation.
Long-Expected Inconsistency Fixes
The addition of an Abstract Syntax Tree (AST).
The introduction of Uniform Variable Syntax.
The semantics for variable-variables/properties (“({$obj->$properties}[‘name’]” instead of “$obj->{$properties[‘name’]}”).
Enhanced Performance
Changes introduced in phpng illustrate the improved performance of PHP 7. As a result, we should get rapid adoption in a case of smaller hosts. The improvement of performance relies on substantial memory savings. possible due to optimization of internal data structures.