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.
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.
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.
<?php function reverseString(String $str) : String { return strrev($str); } print(reverseString(1234));
We specify that the $str
parameter must be of type String
and 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.
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.
<?PHP declare(strict_types = 1); function reverseString(String $str): String { return strrev($str); } print (reverseString(1234));
Adding a single declare
instruction 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.
??
Unlike some languages, where you can use the variable name as an expression in an if
expression, and boldly 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. This makes it very verbose, plain code, using if
than other languages, such as in the following example.
<?php if(!isset($_GET['key'])) { $key = 'default-value'; } else { $key = $_GET['key']; }
Even when using a ternary operator, the isset
function is required. With the new null operator ??
You can significantly simplify the code:
<?PHP $key = $_GET['key'] ?? 'default_value';
This use is even more effective in cases of chain checking, requiring one or more other if
.
<?php if (isset($_GET['key']) { $key = $_GET['key']; } else if(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 null
values.
In previous versions of PHP, you could import only one element (class, function, constant) from a specific namespace in one expression using the use declaration. This often led to very repetitive code, such as in the example below ..
<?php use VendorName/LibraryName/ClasName1; use VendorName/LibraryName/ClasName2; use VendorName/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.
<?php use VendorName/LibraryName/{ClasName1, ClassName2. ClassName3};
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 been working 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'
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.
Source: https://habr.com/ru/post/419625/
All Articles