25th Anniversary Savings | 25% Off Dedicated Servers*Shop Now
25th Anniversary Savings | 25% Off VPS Hosting* †††Shop Now
Limited Inventory: High-Performance AMD-Powered Servers Now Available.* Shop Now >

PHP 7 vs PHP 8: A Comparison

Posted on by Kyle Johnson | Updated:
Category: Other | Tags: Comparison, PHP, PHP8
Reading Time: 4 minutes

The team behind the release of PHP 8 boasts in their announcement of better performance, better syntax, and improved type safety. PHP 8 is faster than PHP 7, the syntax requires less code, and typing is better supported. These three improvement categories provide a powerful major version release of PHP.

New PHP 8 Features

PHP 8, released in November 2020, introduces several new features that excite developers. These features bring parity with newer languages and breathe new life into a long-running, successful project. Here are a few new features to look forward to in PHP 8.

Named Arguments

Named arguments allow developers to label each passed variable without creating a temporary variable. In the following example, each argument is given context with a name. This method eliminates optional parameters without passing empty values as placeholders, such as false or null, or otherwise passing default values.

<?php

function do_the_thing( $one, $two, $three ) { ... }

do_the_thing(
  one: 'that got away',
  two: 'towers',
  three: 'little pigs'
)

In this example, the second argument is omitted without passing a default value.

<?php

function do_the_thing( $one, $two = 'towers', $three = 'little pigs' ) { ... }

do_the_thing(
  one: 'that got away',
  three: 'amigos'
)

Using named arguments also provides context to the passed values without creating temporary variables. Consider the following example. Each argument is provided context by the temporary variable, but this variable is created without ever being used. While this may be helpful it is no longer necessary as named arguments provide a better way to achieve this.

<?php

// php7
do_the_thing(
  $one = 'that got away',
  $two = 'towers,
  $three = 'amigos'
);

// php8
do_the_thing(
  one: 'that got away',
  three: 'amigos'
);

Constructor Property Promotion

Constructor property promotion is a quality-of-life improvement for developers which reduces the amount of code necessary to create an object with simple constructor properties.

In the example below, the class accepts three constructor arguments assigned to their corresponding properties. Note that the property types are specified twice, both in the property declaration and the constructor. These serve two different but very similar functions that must be duplicated.

<?php

class DoTheThingAction {
  
  protected OneCount $one;
  protected TwoCount $two;
  protected ThreeCount $three;

  public function __construct( OneCount $one, TwoCount $two, ThreeCount $three ) {
    $this->one = $one;
    $this->two = $two;
    $this->three = $three;
  }
}

With constructor property promotion, this duplication can be replaced when simply assigning constructor arguments to corresponding properties of the same name. In contrast to the previous example, consider the same class properties are declared and assigned their respective values via the constructor, except the duplication is removed this time.

<?php

class DoTheThingAction {

  public function __construct(
    protected OneCount $one,
    protected TwoCount $two,
    protected ThreeCount $three,
  ) {
    // Nothing else to do here.
  }
}

Union Types

Union types bring flexibility to variable types while also benefiting from type hinting. Without union types, if a variable could be one of two types, like NULL or integer, the type declaration would be omitted and replaced with a docblock comment. The docblock informs the developer and the documentation that multiple types are supported but do not benefit from type hinting.

<?php

// Argument with a single type uses a typehint.
function do_the_thing( ThingOne $thing ) { ... }

/**
 * Argument supporting multiple types looses typehinting.
 * @param ThingOne|ThingTwo $thing
 */
function do_the_thing( $thing ) { ... }

// With untion types, arguments supporting multiple types
// can benefit from typehinting both possible types.
function do_the_thing( ThingOne|ThingTwo $thing ) { ... }

Match Expression

Match expressions closely resemble switch statements but can often be a better fit. Consider the example of creating an object, the type of which is determined by a string. Using a switch statement, we evaluate the string and assign the appropriate object to a temporary variable.

<?php

switch( $type ) {
  case 'one':
    $object = new ThingOne;
    break;
  case 'two':
    $object = new ThingTwo;
    break;
  case 'three':
    $object = new ThingThree;
    break;
}

With the match expression, we can eliminate the boilerplate required to make a switch statement to achieve this dynamic assignment. No longer is each case separated by a break, nor is the object variable assigned in multiple places.

<?php

$object = match( $type ) {
  'one' => new ThingOne,
  'two' => new ThingTwo,
  'three' => new ThingThree,
}

While the switch statement is still a useful, powerful feature, supporting multiple cases with a single expression and cascading evaluation, the increased complexity is often unnecessary for many use cases. In this case, the match expression can be a better fit.

Nullsafe Operator

The nullsafe operator is another quality-of-life improvement implemented in PHP8. When accessing a property multiple levels deep, checking for null values each step down the line is no longer necessary, as shown in the following example.

<?php

if( null !== $user ) {
  if( null !== $user->profile ) {
    echo $user->profile->getAvatar();
  }
}

By contrast, consider the reduced overhead when using the nullsafe operator. Each property down the line is safely checked for null before calling the next property.

<?php

echo $user?->profile?->getAvater();

New PHP 8 Functions

Strings also received some much-needed attention in PHP 8, including new functions and a Stringable interface. These new functions will replace some custom, but common, functionality with first-party functions which will introduce consistency across projects while reducing logical overhead.

String Contains, String Starts With, and String Ends With

The new string methods provide a sane way of handling substrings without needing to rely on the position of that string. Below are some examples to show the difference in complexity.

<?php

// php7 - Check that the string has a position
// and account for a position of 0
false !== strpos( 'thing-one', 'one');

// php8
str_contains( 'thing-one', 'one' );
<?php

$haystack = 'thing-one';
$needle = 'thing';

// php7
0 === strpos( $haystack, $needle );

// php8
str_starts_with( $haystack, $needle );
<?php

$haystack = 'thing-one';
$needle = 'one';

// php7
strpos( $haystack, 'one') == ( strlen( $haystack ) - strlen( $needle ) );

// php8
str_ends_with( $haystack, $needle );

PHP 7 vs PHP 8 Performance

PHP 8 introduces another increase in performance for PHP, continuing the progressive improvements of each minor release of PHP 7. While the performance increase is not as stark as the difference between PHP 5 and PHP 7, there is a steady increase in performance with each release.

Final Thoughts

PHP 8 is a welcome update for developers, providing changes they can use out of the box. When comparing PHP 7 vs PHP 8, users see performance and speed differences along with the new features and functions. It may be worth a try if you still need to upgrade to PHP 8 on your Windows or Linux test machines.

Need to start a new project with PHP 8 on your server? You can run it on Liquid Web’s VPS Hosting, Cloud Dedicated Servers, and Dedicated Servers, among others. Contact our sales team to get set up.

About the Author: Kyle Johnson

Senior Developer @GiveWP (@LiquidWeb), formerly @NinjaForms. Afternoons are spent with my wife wrangling JSON, a black lab.

Latest Articles

PHP 7 vs PHP 8: A Comparison

Read Article

How to Create a Symbolic Link

Read Article

What Is A Private VPS Parent?

Read Article

Managed Hosting vs Unmanaged VPS Hosting

Read Article

Why Is Your IP Address Blocked?

Read Article