PHP7 powering the web a whole lot Better
PHP is one of the most popular programming languages for most of the web development companies today. 2015 has given a significant boost to PHP after eleven years of its release i.e. 5.0. At the end of 2015, PHP 7 was released which has brought many new features and impressive performance boosters.
But how will this result on your current PHP codebase? What is revised in it? And is it safe to update?
This post will solve your queries and give you a complete guide to PHP 7.
An Introduction
PHP 7 is a brand new version of the engine coming under the code name of .
The Zend engine has been supplying PHP since 1999. It is important to note that Zend should not to confused with the Zend Framework, an open-source execution engine which is in C language that interprets the PHP language. The older version i.e. PHP 5.X series utilized Zend Engine II. It assisted in enhancing the functionality of the primary engine and added an extensible object model with significant performance enhancement to the language.
The Name’s PHP 7 (Not 5.7)
PHP 5.7 existed in the past as an experimental project but never reached the production phase. It was due to the Unicode problems that were supposed to be solved in version 5.7 which were unsuccessful, hence because of too many complications, and this kind of ruined things for everyone, it was decided to come up with .
Also Read:
New Features of PHP 7
Due to a new version of Zend Engine, PHP 7.0.0 offers the following features:
- Constant arrays using define()
- Spaceship Operator
- Return Type Declarations
- Scalar Type Declarations
- PHP 7 enable to use Anonymous Classes
- The null coalescing Operator (??)
- Closure::call()
- Filtered unserialize()
- IntlChar
- Anonymous Classes.
- Expectations
- Generator Return Expressions
- Generator Delegation
- Unicode codepoint escape syntax
- CSPRNG Functions
- preg_replace_callback_array()
- Session options
- Integer division with intdiv()
- Group use Declarations
Some handpicked features of PHP 7 are explained here.
Scalar Type Deceleration
It is one of the most controversial change. The addition of this feature involved vote that almost passed. Multiple RFCs followed this, and a whole lot of confusion occurred which ultimately ended with moving the original RFC.
For the end-users, it only means that you can type-hint with scalar types. Specifically: integers, floating point numbers, string, and booleans. Default type-hints are non-strict, which denotes that they pressurize the original type to the type-hint type float (1.0).
1 2 3 4 5 6 7 8 | <?php //use Coercive mode function sumOfInts(int...$ints) { return array_sum($ints); } var_dump(sumOfInts(2, 3‘, 4.1)); |
Return type declarations
The new PHP 7 adds support for return type declarations. It is just like argument type declarations using the same types which are available for return type declarations. The return type declarations specify the type of the value that will be returned from a function.
1 2 3 4 5 6 7 8 9 10 | <?php function arraysSum(array...$arrays): array { return array_map(function(array $array): int { return array_sum($array); }, $arrays); } print_r(arraysSum([1,2,3], [4,5,6], [7,8,9])); |
It will result into:
1 2 3 4 5 6 | Array ( [0] => 6 [1] => 15 [2] => 24 ) |
Null coalescing operator
The null coalescing operator (??) act as a syntactic sugar for using a ternary in conjunction with isset(). If it exists it return its first operand and is not NULL; otherwise it returns its second operand.
1 2 3 4 5 6 7 8 9 10 11 12 | <?php // Fetches the value of $_GET[‘user’] and returns ‘nobody’ // if it does not exist. $username = $_GET[‘user’] ?? ‘nobody’; // This is equivalent to: $username = isset($_GET[‘user’]) ? $_GET[‘user’] : ‘nobody’; // Coalescing can be chained: this will return the first // defined value out of $_GET[‘user’], $_POST[‘user’], and // ‘nobody’. $username = $_GET[‘user’] ?? $_POST[‘user’] ?? ‘nobody’; ?> |
Spaceship operator
The spaceship operator is used for comparing two expressions which is done according to PHP’s usual type comparison rules. It returns -1, 0 or 1 when $a is respectively less than, equal to, or greater than $b.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php // Integers echo 1 <=> 1; // 0 echo 1 <=> 2; // -1 echo 2 <=> 1; // 1 // Floats echo 1.5 <=> 1.5; // 0 echo 1.5 <=> 2.5; // -1 echo 2.5 <=> 1.5; // 1 // Strings echo “a” <=> “a”; // 0 echo “a” <=> “b”; // -1 echo “b” <=> “a”; // 1 ?> |
Constant arrays using
In PHP 5.6, Array were defined with const. But now with the PHP 7 Array constants are defined with define().
1 2 3 4 5 6 7 8 9 | <?php define(‘ANIMALS’, [ ‘dog’, ‘cat’, ‘bird’ ]); echo ANIMALS[1]; // outputs “cat” ?> |
PHP 7 enable to use Anonymous Classes
PHP 7 allow using Anonymous Classes which means a class without a name. The object it instantiates has the same functionality as an object of a named class. If they are used well, they may speed up coding as well execution time.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <?php interface Logger { public function og(string msg); } class Application { private $logger; public function getLogger(): Logger { return $this->logger; } public function setLogger(Logger $logger) { $this->logger = $logger; } } $app = new Application; $app->setLogger(new class implements Logger { public function log(string $msg) { echo $msg; } }); var_dump($app->getLogger()); ?> |
The example will result into:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | object(class@anonymous)#2 (0) { } Closure::call() Closure::call() is shorthand way of temporarily binding an object scope to a closure. <?php class A {private $x = 1;} // Pre PHP 7 code $getXCB = function() {return $this->x;}; $getX = $getXCB->bindTo(new A, ‘A’); // intermediate closure echo $getX(); // PHP 7+ code $getX = function() {return $this->x;}; echo $getX->call(new A); The above example will result into: 1 1 |
Filtered unserialize()
It is useful to provide provide better security while unserializing objects on untrusted data. It prevents possible code injections by enabling the developer to whitelist classes that can be unserialized.
1 2 3 4 5 6 7 8 9 10 | <?php // converts all objects into __PHP_Incomplete_Class object $data = unserialize($foo, [“allowed_classes” => false]); // converts all objects into __PHP_Incomplete_Class object except those of MyClass and MyClass2 $data = unserialize($foo, [“allowed_classes” => [“MyClass”, “MyClass2”]]); // default behaviour (same as omitting the second argument) that accepts all classes $data = unserialize($foo, [“allowed_classes” => true]); |
IntlChar
The new IntlChar class seeks to provide additional ICU functionality. The class itself defines a number of static methods and constants that can be used to manipulate unicode characters.
1 2 3 4 5 6 7 8 9 | <?php printf(‘%x’, IntlChar::CODEPOINT_MAX); echo IntlChar::charName(‘@’); var_dump(IntlChar::ispunct(‘!’)); The above example will output: 10ffff COMMERCIAL AT bool(true) |
Expectations
Expectations are a backwards compatible enhancement to the older assert() function. They allow for zero-cost assertions in production code, and provide the ability to throw custom exceptions when the assertion fails.
1 2 3 4 5 6 7 | <?php ini_set(‘assert.exception’, 1); class CustomError extends AssertionError {} assert(false, new CustomError(‘Some error message’)); ?> |
The above example will output:
Fatal error: Uncaught CustomError: Some error message
Generator Return Expressions
This feature was introduced into PHP 5.5. It builds upon the generator functionality. This value can be fetched using the newGenerator::getReturn(), method, which may only be used once the generator has finishing yielding values.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php $gen = (function() { yield 1; yield 2; return 3; })(); foreach ($gen as $val) { echo $val, PHP_EOL; } echo $gen->getReturn(), PHP_EOL; |
The above example will output:
1 2 3 | 1 2 3 |
Unicode codepoint escape syntax
Here Unicode takes the codepoint into hexadecimal form and interprets the same codepoint into doubled quoted string or heredoc- UTF-8.
1 2 3 4 5 6 7 | echo “\u{aa}”; echo “\u{0000aa}”; echo “\u{9999}”; The above example will output: ª ª (same as before but with optional leading 0‘s) 香 |
Wrapping up
PHP is upgraded to improve its performance. The improved version has introduced as phpng. The increased performance may ensure quick adoption, especially from smaller hosts, as they will be able to host maximum users on the same hardware. In addition to performance, PHP 7 is also expected to save a substantial amount of memory, as optimization of internal data structures is one of the fundamental ways in which performance enhancement have been achieved. Let’s go PHP!
Tutorial Categories:
Tutorial Categories:
PHP 5.7? Technically, that’s correct in that the last branch of the 5.x series is 5.6 not 5.7. But the reason the PHP project released this is version 7 is that it introduced new features which break compatibility with its predecessor.
Did you mean to instead clarify that PHP 7 skipped the illfated PHP 6 branch (which is where the Unicode work was attempted)?