Here’s a quick overview of the new features introduced in PHP 7:
- Scalar Type Declarations: PHP 7 introduced scalar type declarations, allowing developers to specify the type of function parameters and return values. Supported scalar types include
int
,float
,string
, andbool
. This helps improve code clarity and enables better type checking. Type declarations are optional and do not affect runtime behavior. - Return Type Declarations: PHP 7 introduced return type declarations, allowing developers to specify the type of value that a function should return. This helps enforce stricter type checking and improves code readability.
- Null Coalescing Operator: PHP 7 introduced the null coalescing operator (
??
), which provides a shorthand way of handling null values. It allows you to specify a default value that will be used if a variable is null. This simplifies null value handling and reduces the need for verbose null-checking code. - Spaceship Operator: PHP 7 introduced the spaceship operator (
<=>
), also known as the combined comparison operator. It provides a concise way to compare two values and returns -1, 0, or 1 based on the comparison result. This is especially useful for sorting and ordering operations. - Group Use Declarations: PHP 7 introduced group use declarations, allowing multiple classes to be imported from the same namespace using a single
use
statement. This improves code readability by reducing the number ofuse
statements needed. - Anonymous Classes: PHP 7 introduced support for anonymous classes, which are classes that are defined without a name. Anonymous classes are useful when you need to create a one-time use class and don’t want to define a separate class file for it.
- Throwable Interface: PHP 7 introduced the
Throwable
interface, which serves as the base interface for both exceptions and errors. This allows for better handling and catching of both types of throwable objects. - Generator Delegation: PHP 7 introduced generator delegation, allowing generators to yield values from other generators. This enables the creation of more modular and reusable generator functions.
These are some of the major features introduced in PHP 7. The release also includes performance improvements, bug fixes, and other smaller language enhancements that contribute to a better development experience.
Scalar type hints
Type hints have been available in PHP for while now. Unfortunately they were restricted to classes, arrays and callables.
As of PHP 7, the scalar types (integers, floating point numbers, booleans and strings) can also be used as type hints.
<?php
/**
* Scalar type declarations
*/
//declare(strict_types=1);
function add(int $a, int $b) {
return $a + $b;
}
var_dump(add(1,2));
var_dump(add("1","2"));
I’m happy with this PHP 7 feature, because it allows developers to ensure a better input consistency of a function/method interface. By default “coercive mode” is enabled. This restricts PHP from throwing a type error when the types don’t exactly match, but when a conversion is still possible.
If you enable “strict mode” (by uncommenting line 6), a type error is thrown when the signatures don’t match.
Return type declarations
Whereas type hints ensure input consistency, return type declarations ensure output consistency.
We use a colon before the opening curly brace of a function to hint the return type.
<?php
/**
* Return type declarations
*/
//declare(strict_types=1);
function add(int $a, int $b): int{
return (string)($a + $b);
}
var_dump(add(1,2));
The same strictness rules apply as with the type hints: if “strict mode” is disabled, return values that can be converted to the preferred type are allowed. If you enable “strict mode” this code will throw a type error.
Anonymous classes
Anonymous classes are useful for simple one-off objects. With anonymous classes you can define a class and instantiate an object inline.
<?php
/**
* Anonymous classes
*/
$foo = new class {
public function foo() {
return “bar”;
}
};
var_dump($foo,$foo->foo());
The Closure::call() method
Closures are anonymous functions that are declared inline and assigned to a variable. It can be used as a callback for later execution. In PHP 5 it was already possible to bind an object to the scope of the closure as if it was a method.
The “call” method is one of the PHP 7 features that was introduced to simplify the process.
<?php /** * Closure::call() */ class Foo { private $foo = 'bar'; } $getFooCallback = function() { return $this->foo; }; //PHP5 style $binding = $getFooCallback->bindTo(new Foo,'Foo'); echo $binding().PHP_EOL; //PHP7 style echo $getFooCallback->call(new Foo).PHP_EOL;
Generator delegation
Generators are cool, but sometimes hard to explain. Ironically using them is surprisingly simple. It’s all about the “yield” keyword. By using “yield”, a generator is returned with the value that is yielded. A generator implements an iterator which makes it easy to use in while or for loops.
In PHP 7 generator delegation was introduced. This means a generator from another function can be addressed.
<?PHP
/* Generator delegation */
function gen()
{
yield 1;
yield 2;
yield from gen2();
}
function gen2()
{
yield 3;
yield 4;
}
foreach (gen() as $val)
{
echo $val, PHP_EOL;
}
Generator return expressions
As mentioned: by using the yield keyword, values can be yielded and iterator over. But return values are ignored by generators.
In PHP 7 the “getReturn” method was added to the Generator class to allow return values in generators.
<?php
/**
- Generator return expressions
*/
$gen = (function() {
yield 1;
yield 2;
return 3;
})();
foreach ($gen as $val) {
echo $val, PHP_EOL;
}
echo $gen->getReturn(), PHP_EOL;
The null coalesce operator
The null coalesce operator is a shorthand for checking if a value is set and not null within inline comparisons. Instead of doing the same old “isset” check over and over again, just use “??” to return the value if it is set (and not null) or an alternative value instead.
<?php /** * Null coalesce operator */ $array = ['foo'=>'bar']; //PHP5 style $message = isset($array['foo']) ? $array['foo'] : 'not set'; echo $message.PHP_EOL; //PHP7 style $message = $array['foo'] ?? 'not set'; echo $message.PHP_EOL;
The space ship operator
The so-called “space ship operator” makes it easier to compare values. Instead of returning a typical true/false value, the space ship operator returns one of the follow values based on the result of the evaluation:
- 0 when both values are equal
- -1 when the left value is less than the right value
- 1 if the left value is greater than the right value
<?php /** * Space ship operator */ $array = [ "1 <=> 1" => 1 <=> 1, "1 <=> 2" =>1 <=> 2, "2 <=> 1" => 2 <=> 1 ]; var_dump($array);
Throwables
A big change in PHP 7 is the fact that errors are no longer raised the way they used to be raised. Errors now behave in a similar way as exceptions. They both inherit from the Throwable interface.
This means that errors can now be caught in a try/catch block. You can catch both exceptions and errors as Throwables, but you can also catch errors as Error objects.
There are event different kinds of errors we can catch:
- ArithmeticError
- AssertionError
- DivisionByZeroError
- ParseError
- TypeError
This is also a backwards compatibility break because custom error handlers might not be triggered. If you have a parse error in an eval function, it will throw a ParseError instead of just returning false. Watch out!
<?php /** * Throwable interface */ //Error as Throwable try { sqdf(); } catch (Throwable $t) { echo "Throwable: ".$t->getMessage().PHP_EOL; } //Exception as Throwable try { throw new Exception("Bla"); } catch (Throwable $t) { echo "Throwable: ".$t->getMessage().PHP_EOL; } //Error try { sqdf(); } catch (Error $e) { echo "Error: ".$e->getMessage().PHP_EOL; } catch (Exception $e) { echo "Exception: ".$e->getMessage().PHP_EOL; } //Exception try { throw new Exception("Bla"); } catch (Error $e) { echo "Error: ".$e->getMessage().PHP_EOL; } catch (Exception $e) { echo "Exception: ".$e->getMessage().PHP_EOL; } //Type error try { function add(int $a, int $b):int { return $a + $b; } echo add(array(), array()); } catch (TypeError $t) { echo "Type error: ".$t->getMessage().PHP_EOL; }
Level support for the dirname() function
The dirname function is used more often than you would think. It is the ideal function to refer to directories in a relative way.
But when you want to go a couple of levels up, you end up nesting dirname calls and that will eventually lead to confusion.
As of PHP 7 the dirname function has a second argument that indicates how many levels your going up the directory tree. If you don’t enter a value, 1 is the default.
<?php /** * Dirname levels */ echo dirname('/usr/local/bin').PHP_EOL; echo dirname('/usr/local/bin',1).PHP_EOL; echo dirname('/usr/local/bin',2).PHP_EOL; echo dirname('/usr/local/bin',3).PHP_EOL;
The Integer division function
Maybe not one the most important PHP 7 features, but still worth mentioning: the intdiv function returns the integer value of a division whereas regular divisions can result in a float being returned.
<?php /** * Integer division */ var_dump( intdiv(10, 3), (10/3) );
Uniform variable syntax
In PHP 7 the “uniform variable syntax” was introduced. This standard changes the way indirect access to array keys, properties and methods is evaluated. The PHP 7 interpretation enforces a strict left-to-right evaluation.

This is also considered a backwards compatibility break. It is advised to change your code and use curly braces to enforce the evaluation order if you want your code to work on PHP 7.
Performance
Let’s not forget to mention that the performance of PHP 7 is supposed to be impressive. Some say that it’s twice as fast as PHP 5(.6) others use even more dazzling numbers. I’m confident that it perform great and I’m curious to see the average numbers once people start using it.
