My favorite PHP7 features overview

Original author: Jody LeCompte
  • Transfer


When people discuss changes in PHP7, the most common thing you hear is a significantly improved engine that boasts faster execution speed and significantly less memory when comparing regular PHP applications such as Drupal, WordPress and MediaWiki.


Don't get me wrong, this is all of course great! I managed to transfer some outdated CodeIgniter applications to PHP7 and achieve much higher performance with a few changes in the code base. However, PHP7 also adds several new features that can help optimize existing code or improve the quality of writing new code. Here I laid out a few of my favorite features.


Scalar parameter and return type declared


PHP had type declarations up to version 7, but was limited to only objects and arrays. PHP7 now provides support for all scalar types and offers two different type declarations.


Forced:


This is the default ad type and simply means that the PHP runtime will attempt to supply values ​​when necessary. Take, for example, the following code.


<?phpfunctionreverseString(String $str) : String{
    return strrev($str);
}
print(reverseString(1234));

We indicate that the parameter $strmust be of type Stringand the return value must also be of type String. Therefore, when we transmit the number 1234, it is forcibly translated into the string "1234" and translated without errors.


Strict:


The second, strict type, is included with the help of the flag added to the beginning of each file. When it is turned on, the interpreter does not give the type, as in the example above, it responds with an error and stops the execution of the script.


<?PHPdeclare(strict_types = 1);
functionreverseString(String  $str): String{
    return  strrev($str);
}
print (reverseString(1234));

By adding a single declareinstruction at the very beginning of the file, in the same code as before, we now receive the following error message:


Fatal error: Uncaught TypeError: Argument 1 passed to reverseString () must

A small addition: when you enable strict mode, this also applies to the built-in functions and PHP functions loaded from extensions.


Null Operator ??


Unlike some languages, where you can use a variable name as an expression in an expression ifand safely assume that if the value is undefined or empty, the value will be false, PHP will throw an error about an undefined variable, index, etc. It does very verbose, plain code, using ifother languages ​​than, for example, in the following example.


<?phpif(!isset($_GET['key'])) {
    $key = 'default-value';
} else {
    $key = $_GET['key'];
}

Even when using a ternary operator, a function is needed isset. With the new null operator, ??you can significantly ease the code:


<?PHP
$key = $_GET['key'] ?? 'default_value';

Such use is even more effective in cases of chain checking requiring one or more other operators if.


<?phpif (isset($_GET['key']) {
    $key = $_GET['key'];
} elseif(isset($_POST['key'])) {
    $key = $_POST['key'];
} else {
    $key = 'default value';
}
// Versus
$key = $_GET['key'] ?? $_POST['key'] ?? 'default value';

Small addition: If you are working with JavaScript, you can do things like this:


const value = 0 || false || 'hello';
console.log(value); // hello

This will not work in PHP, and the equivalent PHP code will set the value to 0, since the new operator only works with nullvalues.


Group Use Declarations


In previous versions of PHP, you could import only one element (class, function, constant) from a specific namespace in one expression using declarations use. This often led to very repetitive code, such as in the example below ..


<?phpuseVendorName/LibraryName/ClasName1;
useVendorName/LibraryName/ClasName2;
useVendorName/LibraryName/ClasName3;

When grouping, the above can be abbreviated, as shown in the example below, which allows us to get a cleaner and more visual code, what is imported and from where.


<?phpuseVendorName/LibraryName/{ClasName1, ClassName2. ClassName3};

Constant arrays


Named constants are a very valuable tool in PHP. One common use case is to improve code readability by providing semantic names to arbitrary data, such as colors, RGB values, or magic numbers in code that are ambiguous and can be confusing in other cases.
Anyone who has worked with PHP for a long time has likely seen an application with a constant file (or even several files) that contains dozens, if not hundreds, of named constants requiring long and descriptive names to avoid name conflicts.


<?php
define('COLOR_RED', '#f44141');
define('COLOR_BLUE', '#4286f4');
define('COLOR_GREEN', '#1ae01e');
define('COLOR_PURPLE', '#f309f7');
define('COLOR_ORANGE', '#ef7700');

Named constants, in addition to the previously supported data types, can be both indexed and associative arrays. This will help more accurately group the many named constants that you may have in your application.


<?php// В качестве ассоциативного массива
define('COLORS', [
    'red' => '#f44141',
    'blue' => '#4286f4',
    'green' => '#1ae01e',
    'purple' => '#f309f7',
    'orange' => '#ef7700',
]);
echo(COLORS['red']); // #f44141// Как индексированный массив
define('COLORS', [
    'red',
    'blue',
    'green',
    'purple',
    'orange',
]);
echo(COLORS[0]); // 'red'

Conclusion


There are some other great new features I haven’t mentioned, such as anonymous classes and the spaceship operator. So definitely check the PHP.net documentation for more information. Thank you for taking the time to read all this and please leave any questions or comments below.


Thanks berez for the comments.


Also popular now: