Article Image

PHP 8- All You Need to Know to Upgrade

1st April 2022

PHP 8 has been officially released for general users on November 26, 2020.

This new update brings a number of powerful features and optimizations to the language. While many RFCs have already been accepted and introduced, it’s time to immerse ourselves in some of the most exciting additions that have made PHP faster and more secure.

You might need to improve your code so it can run on PHP 8. If you’ve stayed up to date with the new releases, the update shouldn’t be too hard because most of the breaking changes were deprecated before in the 7.x versions. And don’t worry – all these deprecations are listed in this article.

Besides breaking changes, in addition to speed, PHP 8.0 delivers new features such as the much anticipated JIT compiler, union types, attributes, and much more. We’ll take a look at these as well.

PHP 8 Features that Will Upgrade Your Performance

As a long-time PHP developer, it’s a joy to see PHP 8 bring so many useful updates, like Named Arguments which let you validate data into a function based on their argument name instead of the argument order. And then, in the previous versions, the only way to declare union types could only be indicated in phpdoc annotation comments, but now these can be made directly.

All these attributes are an amazing improvement to the reflection API. Here’s a look at some of the great new PHP 8 features:

Just-In-Time (JIT) Compiler

JIT was already available in PHP since v7.4 as a testing tool, but its performance and usability are much improved in the PHP 8 version. By design, JIT was available in disabled mode to conduct experiments and evaluate the other variables in PHP 7.4.

JIT will increase the speed of PHP 8 applications due to how it handles the compilation of the PHP scripts. It is very simple in terms of V8, HHVM, PyPy, and other modern PHP JIT, but it raises the degree of total PHP complexity, the possibility of new bugs, and the cost of creation and maintenance.

Now officiated in PHP mechanism, the new and improved JIT compiler lets you execute the application code faster as compared to the traditional interpreter.

The nullsafe operator

This RFC proposes the new nullsafe operator ?-> with complete short-circuiting.

If you already know the null coalescing operator, you’re already familiar with its weaknesses: method calls do not work. It would help if you had intermediate checks instead or rely on optional helpers that some frameworks provide:

Named arguments

With named arguments, developers can pass in values to a function by defining the value name so that you don’t have to take their order into account. You can also ignore optional parameters. Named arguments make the code easier to understand because the names of the arguments are descriptive.

Attributes

Attributes, usually known as annotations in other languages, provide a way to add metadata to classes without having to parse docblocks.

Here’s an example:

Match expression

The standout feature I was able to experience with PHP 8, which made coding easier, is match expressions. Developers are now able to return a value based on the given input, without even using additional keywords.

You might call it the switch expression’s big brother: match expressions can return values, need no break statements, it can combine conditions, uses strict comparisons of types, and does not coerce any type.

It looks like this:

Inheritance with private methods

Earlier, PHP used public, protected, and private methods to apply the same inheritance checks. In other words, the same method signature rules as the protected and public methods should be followed by private methods. Because of this, children’s classes would not be able to use private methods.

This updated PHP 8 feature has modified the behaviour, so these inheritance checks are no longer performed on private methods. In addition, it did not make sense to use the final private feature, so doing so would now cause a warning:

Warning: Private methods cannot be final as other classes never override them

Weak Maps

Based on the WeakMap, RFC introduced in PHP 7.4, PHP 8 introduces a WeakMap implementation. WeakMap has references to objects that do not prevent the collection of garbage from those objects.

They also introduce caches that contain references to entity classes to improve the performance of relationships between entities, taking the example of ORMs. As long as this cache has a reference to them, these entity objects cannot be garbage collected, even though the cache is the only thing referencing them.

If this caching layer instead uses weak references and maps, PHP will collect these objects when they are no longer referred to by anything else. Weak maps can offer a better, more resource-friendly way of dealing with these objects, especially in the case of ORMs, which can handle many hundreds, if not thousands, of entities within a request. Here’s what weak maps look like, with an example from the RFC:

Type annotations for internal functions

This was a long-running problem, and with all the improvements made to PHP in previous versions, it was finally solvable. This implies that complete type information will be reflected in internal functions and methods.

ext-JSON always available

It is no longer possible to compile PHP without the enabled JSON extension. Since JSON is so commonly used, instead of ensuring the extension exists first, the best developers can always depend on it being there.

Consistent type errors

In PHP, user-defined functions throw TypeError, but internal functions do not. They emit warnings instead and return null. The behaviour of internal functions has been made consistent throughout PHP 8.

The @ operator no longer silences fatal errors

This change may expose errors that were hidden before PHP 8. On your production servers, make sure to set display_errors=Off.

Default error reporting level

Instead of all but E NOTICE and E DEPRECATED, it’s now E ALL. This means that many previously silently ignored errors but possibly already existed before PHP 8 could pop up.

Namespaced names being a single token

PHP is used to interpret each part of a namespace (separated by a backslash \) as a sequence of tokens. This RFC changed that behaviour, meaning reserved names can now be used in namespaces.

Saner numeric strings

When it finds numbers in strings, the PHP-type system attempts to do several smart things. This will make the behaviour more transparent and consistent.

Saner string to number comparisons

In PHP 8, this RFC addresses the very strange case where 0 = = “foo” results in true. There are several other edge instances like that one, and they are fixed by this RFC.

Stable Sorting

Algorithms for sorting were unreliable before PHP 8. This implies that there was no guarantee of the order of equal elements. The behaviour of all sorting functions is modified by PHP 8 to stable sorting.

Stop Wasting Time on Servers

Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.

Start Free

New PHP Functions

New str_contains() function

Some may argue it’s long overdue, but essentially we no longer have to rely on strops() to know whether there’s another string within a string.

New str_starts_with() and str_ends_with() functions

These two functions are long overdue and are now part of the core.

New fdiv() function

The new fdiv() function has similar ability as the fmod() and intdiv() functions, that allows for division by 0. Instead of getting errors, you’ll get INF, -INF, or NAN, depending on the scenario.

get_debug_type() function

The new get_debug_type function always returns the true native type of variables. It returns a return native type names, e.g., int rather than integer, double instead of float.

get_debug_type() function helps in

  • Error reporting
  • Debugging
  • Business logic

Introducing the Latest Version Of PHP 8 on Cloudways

While Cloudways had already introduced PHP 8.0 to its users, this is now available to all new and existing accounts located in the packaging settings. We highly encourage you to keep your PHP version updated, because of the new features introduced to the language and keep yourself updated to the platform, but do not yet recommend you to upgrade to PHP 8.x on your live production servers, especially if you are using the Laravel framework or any other PHP based CMS. If you create a new web app without Laravel and WordPress, you may freely give PHP 8 a try.

Switching PHP versions on Cloudways

Scroll down the side menu and click on Settings and Packages. Right at the top are the packages for the PHP version, which you can switch from PHP 7.x to PHP 8.0.

As mentioned earlier, it’s highly recommended that you do not upgrade if you run a Laravel Framework or any PHP-based CMS live website. If you create a new web application without any PHP framework or PHP-based CMS or running a website that is not running on any PHP-based CMS, you should be okay to upgrade, but please always proceed with caution.

Select PHP 8 from the drop-down menu.

The upgrade process takes a few minutes. Your server will be upgraded without any downtime.

That’s it! It is easy to change your PHP version using Cloudways Platform.

Next, to verify that PHP 8 is indeed available at your server, launch the SSH terminal from the Master Credentials tab and log in using your credentials.

Use the php -v command to check the installed PHP version.

Final thoughts

Woah! It was some experience to compile and write this article, this is a major update and there will be breaking changes and PHP 8 new features. The best thing to do is to take a peek at the Updating document‘s entire list of breaking modifications.

However, several of these breaking modifications have been deprecated in previous versions of 7. *, so if you have kept up-to-date over the years, upgrading to PHP 8 should not be all that difficult.

In my opinion, PHP 8 is easily the best update to date. Not only has it brought ease to the coding methods and structure, but also optimized the compile time of the code instead of runtime resulting in faster performance of the platform. Small updates in the user interface have also brought more value and user interaction to the language.

A few general changes were also made in the language. Some pre-loaded functions such as create_function() and each() were removed, while the mechanism and working of few functions were modified. The new version is beyond any doubt a step towards cleaning up the language and releasing a lot of those long-awaited and essential highlights and updates.

Let me know in the comments below what you think about the launch of PHP 8, and how it is going to impact the web development arena.

Frequently Asked Questions

Q. Should I upgrade to PHP 8 ?

A: PHP 8 provides improved code execution performance and will expand and improve over time. Better comparisons will get rid of frequent bugs and unexpected behaviors that often plague PHP developers. Resulting Increased Speed and optimized performance. Comparisons between numbers and non-numeric strings now work.

Q. What changed in PHP 8 ?

A: PHP 8 contains numerous highlights and optimizations including named arguments, union types, attributes, constructor property promotion, match expression, nullsafe operator, JIT, and improvements in the type system, error handling, and consistency.

Q. What is the difference between PHP 7.4 and 8 ?

A: One of the many examples is, WordPress on PHP 8.0 can handle 18.4% more requests per second than PHP 7.4. Moreover, Laravel on PHP 8.0 can run 8.5% more requests per second than PHP 7.3. In the event that your site or application is completely congruent with PHP 8.0. Showing that the processing/ compilation speed of PHP 8 is sharp as compared to previous versions.

Q. Is PHP 8 backwards compatible ?

A: PHP 8 new Features also introduces us to unions in PHP 8. This means that there is an issue with backwards compatibility if you implement PHP 8.0 union types, as this will break on sites running PHP 7.4 or below.

Want to get the latest news from us?

© Copyright 2024 EvolutIT