What's new in PHP 7 New Features

For years PHP has evolved with lot's of improvements, fixes and new features. PHP 7 has been released with many improvements and new features. With the improved new PHP you can write better and clean code that runs faster. Here are some of the new features that has been released with PHP 7.

Scalar Typehints

Prior to PHP 7 scalar type-hints are not supported. Using scalar type hints you can enforce functions and methods to accept only values of that particular types, by this way we know for sure that the variable will be of the specified type and lot’s of code can be avoided.

Syntax

function name (type $variable, type $variable) {….}

Example: php7-scalar-typehints.php

interface PHP7InterfaceTest {
}

class PHP7ClassTest implements PHP7InterfaceTest {
}

$arr = ['one', 'two', 'three'];

function php7_typehint_test(
  int $integer,
  bool $boolean,
  string $string,
  float $float,
  array $arr,
  PHP7InterfaceTest $interface,
  PHP7ClassTest $class) {

  // Inside here you can be sure all the values passed will
  // be of it's respective types
  var_dump(func_get_args());
}

// this will pass
php7_typehint_test(3, true, 'A string', 3.333, $arr, new PHP7ClassTest, new PHP7ClassTest);

Correct output

array(7) {
  [0]=>
  int(3)
  [1]=>
  bool(true)
  [2]=>
  string(8) "A string"
  [3]=>
  float(3.333)
  [4]=>
  array(3) {
    [0]=>
    string(3) "one"
    [1]=>
    string(3) "two"
    [2]=>
    string(5) "three"
  }
  [5]=>
  object(PHP7ClassTest)#1 (0) {
  }
  [6]=>
  object(PHP7ClassTest)#2 (0) {
  }
}

Integer TypeHint Error

// integer typehint fail check
php7_typehint_test('thisWillFail', true, 'A string', 3.333, new PHP7ClassTest, new PHP7ClassTest);

Error Output

PHP Fatal error:  Uncaught TypeError: Argument 1 passed to php7_typehint_test() must be of the type integer, string given, called in php7-scalar-typehints on line 26 and defined in php7-scalar-typehints:9
Stack trace:
#0 php7-scalar-typehints(26): php7_typehint_test('thisWillFail', true, 'A string', 3.333, Object(PHP7ClassTest), Object(PHP7ClassTest))
#1 {main}
  thrown in php7-scalar-typehints on line 9

Interface implementation errors

// interface typehint check
php7_typehint_test(3, true, 'A string', 3.333, new stdClass, new PHP7ClassTest);

PHP Fatal error:  Uncaught TypeError: Argument 5 passed to php7_typehint_test() must implement interface PHP7InterfaceTest, instance of stdClass given, called in php7-scalar-typehints on line 28 and defined in php7-scalar-typehints:9
Stack trace:
#0 php7-scalar-typehints(28): php7_typehint_test(3, true, 'A string', 3.333, Object(stdClass), Object(PHP7ClassTest))
#1 {main}

Return Type Declarations

PHP 7 supports the return type declarations with which we can specify the type of value that will be returned from the function. Using return type hint’s it is easy to identify the return type and we can be sure that the particular type specified will be returned as a result of that function or method.

Syntax

function name (type $variable, type $variable): return_type
{
….
}

Example: php7-return-type-declaration.php

// modified the function in the previous example
// ..... .... ....
  PHP7ClassTest $class
): array { // specify the return type of the function


  // Inside here you can be sure all the values passed will
  // be of it's respective types
  return func_get_args();
}

// ..... .... ....

If the function does not return the specified type, then an Uncaught TypeError will be thrown.

Null coalescing operator (??)

The Null coalescing operator (??) is a syntactic sugar for the ternary operator (?:). If the first operand exists it returns it, if not, it returns the second operand.

Syntax

$resulting_value = $operand1 ?? $operand2;

Example: php7-null-coalescing.php

$null_value = null;
$not_a_null_value = 'Hi, i am returned, since i am not a null value';

// instead of using this
// echo $null_value ? $null_value : 'Hi, i am the default value. The variable passed is null' . PHP_EOL;
// the following can be used.
echo $null_value ?? 'Hi, i am the default value. The variable passed is null' . PHP_EOL;
echo $not_a_null_value ?? 'Hi, i am the default value. The variable passed is null';

// Output
Hi, i am the default value. The variable passed is null
Hi, i am returned, since i am not a null

Spaceship operator (<=>)

The spaceship operator is used to compare two expressions. It returns 0, -1, 1 when the first expression is equal, less than or greater than the second expression respectively.

Syntax

expression_one <=> expression_two

Example: php7-spaceship-operator.php

$value = 1;
$compare = 1;

// When both expression of equal.
var_dump($value <=> $compare);

$compare = 2;
// When first expression is lesser.
var_dump($value <=> $compare);

$compare = 0;
// When first expression is greater.
var_dump($value <=> $compare);

// Examples of other types and expressions
var_dump(1+2 <=> 2*3); // Will output int(-1)
var_dump('testString' <=> 'test'); // Will output int(1)
var_dump(new stdClass() <=> new stdClass()); // Will output int(0)

Output

// Output
int(0)
int(-1)
int(1)
int(-1)
int(1)
int(0)

Anonymous Classes

Anonymous classes are used for simple use and throw away purpose. An example would be implementing an simple Logging or Error implementations.

Anonymous class like other classes can accept constructor arguments, extends other classes and interfaces and also include traits.

Syntax

(new class[, arguments] [extends] [implements] {
  // include traits
  // methods
});

Example: php7-anonymous-class.php

// Simple error interface
interface ErrorInterface {
  public abstract function showError($msg);
}

// Class containing users based operations
class User {
  
  protected $error;
  
  public function setErrorInterface(ErrorInterface $error) {
    $this->error = $error;
  }

  public function createUser($user) {
    if ($user) {
      echo 'User Cretaed ' . PHP_EOL;
    } else {
      $this->error->showError('Cannot create user..!!!');
    }
  }
}

$userObj = new User();

$userObj->setErrorInterface(
  // Create and pass the anonymous class.
  new class() implements ErrorInterface {
    public function showError($msg) {
      // Send some headers and set other info's
      echo 'Error: ' . $msg . PHP_EOL;
    }
  }
);

// Error will be showed
$userObj->createUser(null);
// This will display user created.
$userObj->createUser('Foo');

// Output
Error: Cannot create user..!!!
User Cretaed 

In the above example, the setErrorInterface method is passed an anonymous class that implements the ErrorInterface interface and the User class uses that anonymous class as an instance and shows error using that object instance of the anonymous class.

Namespace use grouping

This is one of my favourite feature in PHP 7. You can now avoid multiple namespace use statements that looks very awful when there are lot’s of classes to be included from a single namespace.

With namespace grouping, multiple classes from a single namespace can be grouped and included.

Syntax

use some/namespace/{class1, class2, class3 as C3};

Example

namespace Codedodle\Classes;

interface Class1 {
}

interface Class2 {
}

interface Class3 {
}

namespace Codedodle\Posts;

use Codedodle\Classes\{Class1, Class2, Class3 as C3};

class App implements Class1, Class2, C3 {
  
}

Above example shows how to group classes from the Codedodle\Classes namespace into the Codedodle\Posts namespace.

Following are some usefull links,