New Features In PHP 7 – Explained

0
1215
new-features-in-PHP-7

PHP is the most commonly used programming language. PHP 7 is the latest version which is considered to be the revolutionary release. After the release of PHP 7, official support for PHP 5.5 has been ended.

Today, we wil dive into details about the features of PHP 7.

Speed Improvement

PHP community has worked really hard to make PHP at its best. There is a significant increase in speed in PHP 7 as compared to PHP 5.6. Moreover, PHP 7 uses less memory and great perfomance.

Type Declaration

The type declaration is used to set the type of variable. PHP used to set the type of variable automatically without need to set manually. This is why, PHP is considered a weakly typed language. When there is no strict to define the type of variable, you may end with unexpected results without having an error. For example, you may end adding an integer with a string. For this, type declaration comes to rescue you.

Scalar Type hints

PHP 7 has now added Scalar type declaration for int, float, string, and boolean. In the previous versions, there was only type hint for class and array. But in PHP 7, we can use it for more types. It ensures that only correct types of data are passed. There are two types ofscalar type hints i.e. Strict Mode and Non-strict Mode.

Non-strict Mode
By default, scalar type hints are non-strict. So, they will attempt to change the original type to match the type specified by the type-declaration. For example, when you try to pass a string containing number into a function that requires a float, PHP will grab only the number from string. To sum up, without strict types turned on, PHP attempts to cast, or change, these arguments to match the type specified in the function.

function sum(float $a, float $b){
      return $a + $b;
 }

 sum(5, '6');

 //output: 11

Strict Mode
Its a great that you can enable or disable strict mode in PHP. Since by default, strict mode is disabled, we can enable by using declare(strict_types=1); at the top of file before namespace.

If we failed to pass the exact data type as required by the function, it will throw a “Fetal Error”.


This will output a fetal error.

FATAL ERROR Uncaught TypeError: Argument 2 passed to sum() must be of the type float, string given, ...

Return Type Declarations

This is really a great feature in PHP and used a lot more often. We can declare the return type of function. To specify the return type, we add a colon and then the type right before the opening curly bracket. Suppose, if want to return a float type, we will define it as like below.

function sum(float $a, float $b) : float {
      return $a + $b;
 }

 sum(5, '6');

Error Handling

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 different types of error.

  • ArithmeticError
  • AssertionError
  • DivisionByZeroError
  • ParseError
  • TypeError
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;
}

Multi Catch Exception Handling

We can now have multiple catch exception in a single block. Multiple exceptions are separated using a single 'pipe' symbol. This way we can avoid duplicating same code to handle multiple exception types.


Null coalescing Operator

PHP 7 introduces some new operators among them Null coalescing operator is one. This operator is used to check if the value is set and not null. It is denoted by ??. Actually, it is a shorthand to check if value is set and not null.


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

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

Integer Division Function

If you want to return integer value of a division, then there is a new function for you named intdiv() function.


CSPRNG Functions

CSPRNG stands for ‘Cryptographically Secure Pseudo-Random Number Generator’. Two new functions have been added to generate cryptographically secure integers and strings in a cross platform way: random_bytes() and random_int().

Random Bytes

random_bytes generates cryptographically secure pseudo-random bytes. random_bytes function generates an arbitrary length string of cryptographic random bytes that are suitable for cryptographic use, such as when generating salts, keys or initialization vectors.

We should give a number as parameter that the length of the random string that should be returned in bytes. It returns a string containing the requested number of cryptographically secure random bytes.


Random Integers

random_intgenerates cryptographically secure pseudo-random integers. Generates cryptographic random integers that are suitable for use where unbiased results are critical, such as when shuffling a deck of cards for a poker game.

It takes 2 parameter i.e. min and max. min is the lowest value to be returned, which must be PHP_INT_MIN or higher. maxis highest value to be returned, which must be less than or equal to PHP_INT_MAX.

It returns a cryptographically secure random integer in the range min to max, inclusive.

//generate positive integer
var_dump(random_int(100, 999)); //output: int(247)
//generate negative integer
var_dump(random_int(-1000, 0)); //output: int(-878)

Constant arrays using define()

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


Anonymous classes

Support for anonymous classes was added in PHP 7. Anonymous classes are useful when simple, one-off objects need to be created.

They can pass arguments through to their constructors, extend other classes, implement interfaces, and use traits just like a normal class can:

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('Anonymous Classes Example'));

//output: Anonymous Classes Example

Unicode codepoint escape syntax

This takes a Unicode codepoint in hexadecimal form, and outputs that codepoint in UTF-8 to a double-quoted string or a heredoc. Any valid codepoint is accepted, with leading 0's being optional.

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

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

Closure::call()

Closure::call() is a more performant, shorthand way of temporarily binding an object scope to a closure and invoking it.

$getX = function() {return $this->x;};
echo $getX->call(new A);

// output: 1

Consclusion

Okay, so we have seen pretty much about PHP 7. Now, it's time to test these features in real life application. One this is certain that PHP 7 is awesome than previous version. Most of the hosting company have already started to provide PHP 7. You can choose to upgrade to PHP 7 or using the old ones. But, be sure to see the changes and depreciation logs before doing anything in production.

You can also read the new the new features in PHP 7 at its official documentation.

If you want to learn about Implementation of Interface in PHP, you can read this article which explains with real life example.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.