PHP Classes

PHP 7 Migration Guide Part 2: 19 New Exciting Features In PHP 7

Recommend this page to a friend!
  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog PHP 7 Migration Guide...   Post a comment Post a comment   See comments See comments (4)   Trackbacks (0)  

Author:

Viewers: 3,597

Last month viewers: 1

Categories: PHP Tutorials

PHP 7 was a great step forward in the evolution of PHP. Many things were added, changed and removed.

In the first part of this article it was covered the things that were changed or removed and may break your PHP code that ran with the past versions.

Read this article part to learn more in detail about the new features and improvements of PHP 7 that you can take advantage.




Loaded Article
Picture of Atif Shahab Qureshi
By Atif Shahab Qureshi Pakistan

cloudways.com/en/

<email contact>

Contents

Introduction

19 New Exciting Features of PHP 7

Conclusion


Introduction

In the previous part of this article I talked about top backwards incompatible changes of PHP 7. To migrate to the this newer PHP version, you must be well aware of the new features of PHP 7. In this part I will be briefly presenting the features I consider most exciting of PHP 7, in great part based on a list from the PHP manual.

19 New Exciting Features of PHP 7

1. Scalar Type Hinting Declarations 

There are now two forms of scalar type hinting declarations. The first one is default and second one is strict. String, integer, floating point number and boolean values can now be be checked enforced when calling a function or returning a value. Consider the following example:

<?php

// Default mode
function sumOfInts( int ...$ints )
{
return array_sum($ints);
}
var_dump(sumOfInts(2, '3', 4.1)); ?>

Output:

int(9)

The strict mode can be enabled by placing a declare directive at the top like this:

declare(strict_types=1);

Strictness of typing for scalars will be configured on per file basis. However, keep in mind that if a script is included from a parent script that does not enable strict typing, it will not be enabled for the included child script.

2. Return Type Hinting Declarations

PHP 7 also supports the return type hinting declarations. This kind of declarations basically specify the type of value to be returned from a function. Hence, it is very similar to the argument type hinting declarations. Consider the following code:

<?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] )); ?>

Output:

Array
(
[0] => 6
[1] => 15
[2] => 24
)

3. Null Coalescing Operator

A new operator called null coalescing operator (??) has been added in PHP 7. It allows the developers to implicitly use a ternary expression with isset() to determine if a value is set.

In case the value is not set, it evaluates to the value second operand. If the first operand value is set, it evaluates to that value.

Consider the following example to better understand the use of null coalescing operator:

<?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';

?>

4. Spaceship Operator in Comparisons

The spaceship operator was introduced in PHP 7 to help with comparing two expressions. It may evaluate 0,1, or -1. This is useful for array sorting functions that take callback functions that must return one of these 3 values depending on how two array entry values compare.

Comparisons are made according to type comparison rules. Consider the following example.

<?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

?>

5. Define() for Constant Arrays

From now on, in PHP, array constants can be defined with define() function. In previous versions, we could not define array constants not even in classes with the const keyword.

Consider the following example:

<?php

define('ANIMALS', [
'dog',
'cat',
'bird'
]);
echo ANIMALS[1]; // outputs "cat"

?>

6. Anonymous Classes Support

In PHP 7, support for anonymous classes has also been added through new class construct. Anonymous classes can be used to create objects on demand without declaring class separately. Consider the following example.

<?php

interface Logger {
public function log( 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() );

?>

Output:

object(class@anonymous)#2 (0) {
}

7. Unicode CodePoint Escape Syntax

Now you can represent Unicode characters using the Codepoint hexadecimal format. The characters are translated to strings with UTF-8 encoding. Consider the following example:

echo "\u{aa}";
echo "\u{0000aa}";
echo "\u{9999}";

Output:

ª

ª (same as before but with optional leading 0's)

8. Closure::Call() Function For Binding to Objects

The Call function is a PHP 7 method for temporarily binding an object scope to the closure function and then calling it as part of the object. Consider the following example:

<?php

class A {private $x = 1;}

// before PHP 7
$getXCB = function() { return $this->x; };
$getX = $getXCB->bindTo( new A, 'A'); // intermediate closure
echo $getX();

// Starting with PHP 7
$getX = function() { return $this->x; };
echo $getX->call(new A);

?>

Its output will be:

1
1

9. Filtered Unserialize() for Preventing Injection of Unauthorized Class Objects

When calling unserialize you can define which classes of objects are expected to be recreated. It is useful to prevent injection of code of objects by specifying a white list of classes which can be unserialized. Consider the following example:

<?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] );

?>

10. IntlChar Class Helps Manipulating Unicode Text

Intl Class defines constants and static methods for manipulating Unicode characters. This class requires the intl extension to be enabled on your PHP 7 installation. Example:

<?php

printf('%x', IntlChar::CODEPOINT_MAX);
echo IntlChar::charName( '@' );
var_dump( IntlChar::ispunct( '!' ) );

?>

Output:

10ffff
COMMERCIAL AT
bool(true)

11. Expectations Can Throw Exceptions

Traditionally developers used the assert() function to verify important conditions at run time. In PHP 7 you can pass a custom exception object that will be called if the assert condition value is false.

Also in PHP 7 assertions are a built-in construct of the language. This means that if assertions are disabled in the PHP configuration, it is as if the assertion code was not inserted in your PHP code, so they are not evaluated nor executed.

Consider the following example to better understand the concept:

<?php

ini_set( 'assert.exception', 1);
class CustomError extends AssertionError {}
assert(false, new CustomError( 'Some error message' ));

?>

Output:

Fatal error: Uncaught CustomError: Some error message

12. Group Namespace Use Declarations

In PHP7 it is now possible to import multiple constants, functions and classes from same namespace with a single use statement, thus making the code more succinct.

Consider the following example to better understand the concept:

<?php

// Before PHP 7
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;
use function some\namespace\fn_a;
use function some\namespace\fn_b;
use function some\namespace\fn_c;
use const some\namespace\ConstA;
use const some\namespace\ConstB;
use const some\namespace\ConstC;

// PHP 7+ code
use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};

?>

13. Generator Return Values Can also be Used Like Yield

Generators are functions that you can use since PHP 5.5 to return multiple values using the yield command, for instance to be iterated like with array values. Then the generator function is resumed right after the value is used by the calling code right after the yield statement.

Since PHP 7 the return command can also be used to return a value like if it was returned by yield, except that it is the last value returned by the generator function.

If you need to get the actual return value you can used the getReturn() method on the generator function closure object.

The following example demonstrates the concept:

<?php

$gen = (function() {
yield 1;
yield 2;
return 3;
})();
foreach ($gen as $val) {
echo $val, PHP_EOL;
}
echo $gen->getReturn(), PHP_EOL;

?>

Output:

1
2
3

14. Generators Can Delegate on Other Generators

In PHP 7 generators can now delegate to another generator to yield a set of values. Here is an example:

<?php

function gen()
{
yield 1;
yield 2;
yield from gen2();
}

function gen2()
{
yield 3;
yield 4;
}

foreach (gen() as $val)
{
echo $val, PHP_EOL;
}

?>

Output:

1
2
3
4

15. Faster Integer Division with Intdiv()

In PHP 7 Intdiv() can perform integer division faster than the regular / division operator. With the division operator it could return a float and you would need to convert the result to an integer if you just wanted to get the integer part ignoring the remainder.

Consider the following example.

<?php

var_dump(intdiv(10, 3));

?>

Output:

int(3)

16. Advanced Session Options Can be Set at session_start()

In PHP 7 session_start() can take an array of options which will override the configuration directives which are set in php.ini .

The lazy_write option, which is enabled by default, also makes PHP only rewrite session data if it has changed and the read_and_close is passed to session_start().

Consider the following example:

<?php

session_start([
'cache_limiter' => 'private',
'read_and_close' => true,
]);

?>

17. preg_replace_callback_array() Allows to Replace Multiple Expressions

The new function preg_replace_callback_array() allows the developers to specify multiple regular expressions and callback functions to replace the expressions all in a single function call

This is a much cleaner approach then using multiple preg_replace_callback calls.

18. Cryptographically Secure Pseudo Random Number Generators

PHP 7 introduces random_bytes() and random_int() for generating secure random strings and integers. These functions are recommended to be used for cryptography purposes instead of others like rand().

If for some reason you cannot use PHP 7 yet, you can find here an alternative user-land implementation that works with PHP 5.x series contributed by Scott Arciszewski with many other security experts of the PHP community.

19. Correctly Extract Values using List()

Before PHP 7 list() command was not working correctly with objects that implement ArrayAccess interface. That issue is fixed in PHP 7.

Conclusion

In this part, I have presented in detail functions and features which have been introduced or improved in PHP 7.

I work for Cloudways, a company that provides a Managed Cloud Hosting Platform. I would like to take this opportunity to share that our company has recently introduced PHP 7 on its managed cloud servers. You can use it for free on a trial to test the concepts discussed in this blog post.

In next part, I will cover the deprecated features, changed functions, new classes and interfaces.

If you liked this article or you have questions about the new features and improvements of PHP 7, post a comment here now.




You need to be a registered user or login to post a comment

Login Immediately with your account on:



Comments:

2. PHP 7 - New Features - Jatin Parekh (2016-03-29 06:14)
Useful for PHP developers... - 1 reply
Read the whole comment and replies

1. Nice article. - Douglas Haubert (2016-03-29 06:14)
Very usefull approach over PHP 7.... - 1 reply
Read the whole comment and replies



  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog PHP 7 Migration Guide...   Post a comment Post a comment   See comments See comments (4)   Trackbacks (0)