Amit Dhamu

Software Engineer

Some New PHP 7 Features

See below for some new features you can use in PHP 7. This list is not exhaustive.


random_bytes

Generates cryptographically secure pseudo-random bytes

$bytes = random_bytes(5);
var_dump(bin2hex($bytes));

random_int

Generates cryptographically secure pseudo-random integers

var_dump(random_int(100, 999));

Splat Operator

Used to provide an unknown number of arguments to a function like func_get_args.

This was actually added in PHP 5.6

function test(...$arguments) {
    print_r($arguments);
}
 
test(1, 2, 3, 4);
 
// Output
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

Constant Expressions

Previously, PHP required static values for constants. Expressions involving strings and integers can now be used including inside default function arguments.

const ONE = 1;
const TWO = ONE * 2;
 
class C {
    const THREE = TWO + 1;
    const ONE_THIRD = ONE / self::THREE;
    const SENTENCE = 'The value of THREE is ' . self::THREE;
 
    public function f($a = ONE + self::THREE) {
        return $a;
    }
}

Scalar Type Hints

You can now type hint scalar types including strings (string), integers (int), floating-point numbers (float), and booleans (bool).

public function foo(string $name, int $age, bool $single, float $bankBalance)
{
 
}

Return Types

Similar to argument types, you can now declare return types.

public function giveMeAnArray(): array
{
    return [1, 2, 3, 4];
}

Null Coalescing Operator

Returns its first operand if it exists and is not NULL; otherwise it returns its second operand

// PHP 5
$name = isset($_GET['name']) ? $_GET['name'] : '';
 
// PHP 7
$name = $_GET['name'] ?? '';

Spaceship Operator

The spaceship operator is used for comparing two expressions. It returns -1, 0 or 1 when $a is respectively less than, equal to, or greater than $b

// 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
 
// Sorting
// PHP 5
usort($array, function($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
});
 
// PHP 7
usort($array, function($a, $b) {
    return $a <=> $b;
});

Using define with Arrays

Array constants can now be defined with define(). In PHP 5.6, they could only be defined with const.

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

Grouped use Statements

// PHP 5
use some\namespace\ClassA;
use some\namespace\ClassB;
use some\namespace\ClassC as C;
 
// PHP 7
use some\namespace\{ClassA, ClassB, ClassC as C};

Nullable Type

Type declarations for parameters and return values can now be marked as nullable.

function testReturn(): ?string
{
    return 'elePHPant';
}
 
var_dump(testReturn());
 
function testReturn(): ?string
{
    return null;
}
 
var_dump(testReturn());
 
function test(?string $name)
{
    var_dump($name);
}
 
test('elePHPant');
test(null);
test();
 
// Output
string(10) "elePHPant"
NULL
string(10) "elePHPant"
NULL
Uncaught Error: Too few arguments to function test(), 0 passed in...

Void Type

Functions that don't return anything can have a return type of void. If a return is used, it must be empty. You cannot return null.

public function test(): void {
    doStuff();
     
    // Optional: If you need to return, do so like the following
    return;
}

Access Modifiers For Constants

Class constants can now have their visibility declared

class Foo
{
    private const NAME;
    public const AGE;
    protected const DOB;
}

iterable Pseudo Type

iterable can be used as a pseudo return type and argument type for arrays and objects that implement the Traversable interface.

function iterator(iterable $objectOrArray)
{
    foreach ($objectOrArray as $item) {
        //
    }
}

Multi-Catch Exception Handling

Catch multiple exceptions in one block.

// PHP 5
try {
 
} catch (Exception $e) {
    if ($e instanceof CustomException1 || $e instanceof CustomException2) {
        error_log($e->getMessage());
    }
}
 
// PHP 7
try {
 
} catch (CustomException1 | CustomException2 $e) {
    error_log($e->getMessage());
}

 php7

Migrating to PHPUnit 8Aliased Imports in Webpack

Show Comments

Made with by Amit Dhamu.
© MMXX. All rights reserved.