+593 99 022 3684 dime@hassler.ec

A Tour of My Favorite New PHP7 Features

Photo by Artem Bali on Unsplash

One of the more common things you hear when people discuss changes in PHP7 is the significantly improved engine that boasts a faster execution speed and a drastically smaller memory footprint when benchmarking common PHP applications like Drupal, WordPress, and Wikimedia.

Don’t get me wrong, that’s awesome! I was able to move several legacy CodeIgniter applications over to PHP7 and unlock much higher performance with only a few small changes to the codebase. However, PHP7 also brings a few new features to the table that can help to clean up existing code or elevate the quality of new code being written. I’ve outlined a few of my favorites here.

Scalar Parameter & Return Type Declarations

PHP has had type declarations prior to version 7, but was limited to essentially objects and arrays only. PHP7 now brings support for all scalar types to the table and offers two different types of declarations.

Coercive:
This is the default declaration type and simply means that the PHP runtime will attempt to coerce values when needed. Take for example the following code.

 

We specify that the parameter $str should be of type String as well as the return value. So when we pass in the number 1234, it is coerced into a string of ‘1234’ and reversed without error.

Strict:
The second type is strict which is enabled on a file by file basis by a flag added to the top of each file. When enabled, rather than coercing the type as in the example above, it responds with an error and halts execution of the script.

 

By adding the single declare directive at the top of the file, the same code as before, we now get the following error message instead:

Fatal error: Uncaught TypeError: Argument 1 passed to reverseString() must be of the type string, integer given

Small Gotcha: When you enable strict-mode, this also applies to PHP built-in functions and functions loaded from extensions.

Null Coalescing Operator

Unlike some languages where you can use a variable name as an expression in an if statement and safely assume if the value isn’t defined or is empty then it will evaluate false, PHP will throw an error about an undefined variable, index, etc. This makes typical conditional value setting code you find in most languages even more verbose, such as the following example.

 

Even utilizing a ternary can still be unpleasant due to requirement of the isset function. With the new null coalescing operator ( ?? ), you are able to clean the code up significantly as such:

 

The usage is even more effective in cases of chained checks that require one or more else if statements.

 

Small Gotcha: If you code in Javascript, you may be reminded of being able to do things like this:

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

As the name the name would suggest, this would not work in PHP and the equivalent code would set the value to 0 as the new operator only works on null values.

Group Use Declarations

In previous versions of PHP, you could only import a single item (class, function, constant) from a particular namespace in a single statement using the use declaration. This often led to very repetitive code like the example below.

 

With grouping, the above can be cleaned up like the example below allowing for a much cleaner overview of what is being imported or aliased and from where.

 

Constant Arrays

Named constants are a very valuable tool in PHP. One common use case is improving code readability by giving semantic names to arbitrary data like colors to RGB values or magic numbers in the code that are ambiguous otherwise.

Anyone who has worked with PHP for a decent amount of time has likely seen an application with a constants file (or even multiple files) that contain dozens if not hundreds of named constants, requiring long and descriptive names to avoid conflicts.

 

Now named constants, in addition to previously supported data types, can also now be an array with support having been added for numerically indexed arrays and associative arrays. This helps to more cleanly organized the many named constants you may have in your application.

 

Conclusion

There are a few more great new features I didn’t talk about here such as anonymous classes and the spaceship operator. So definitely check out the documentation at PHP.net for more information. Thank you for taking the time to read this and please leave any questions or comments below.

Si continuas utilizando este sitio aceptas el uso de cookies. más información

Los ajustes de cookies de esta web están configurados para "permitir cookies" y así ofrecerte la mejor experiencia de navegación posible. Si sigues utilizando esta web sin cambiar tus ajustes de cookies o haces clic en "Aceptar" estarás dando tu consentimiento a esto.

Cerrar