Reader small image

You're reading from  PHP 8 Programming Tips, Tricks and Best Practices

Product typeBook
Published inAug 2021
Reading LevelIntermediate
PublisherPackt
ISBN-139781801071871
Edition1st Edition
Languages
Right arrow
Author (1)
Doug Bierer
Doug Bierer
author image
Doug Bierer

Doug Bierer has been hooked on computers since his first program, written on a DEC PDP-8, in 1971. In his wide-ranging career, he has been a professional contract programmer since 1978, having written applications in BASIC, PL/I, assembler, FORTH, C, C++, dBase/FoxBase/Clipper, Pascal, Perl, Java, and PHP. He deployed his first website in 1993 while living in San Francisco. He speaks four languages, has traveled extensively, and now resides in Thailand. He also spent some years doing system administration and TCP/IP networking. Some of his technical works include PHP 7 Programming Cookbook and Learning MongoDB 4.x (Packt), as well as Learning PHP and MySQL, Learning PHP Security and Learning Doctrine (O'Reilly Media).
Read more about Doug Bierer

Right arrow

Chapter 9: Mastering PHP 8 Best Practices

In this chapter, you will be introduced to the best practices that are currently enforced in PHP 8. We will cover several significant method signature changes and how their new usage continues the general PHP trend of helping you produce better code. We will also have a look at how private methods, interfaces, traits, and anonymous class usage has changed. Finally, we will discuss important changes in how namespaces are parsed.

Mastering the best practices that will be covered in this chapter will not only move you toward writing better code, but how to avoid the potential code breaks that might arise if you fail to grasp these new practices. In addition, the techniques discussed in this chapter will help you write code that's more efficient than was possible in the past.

In this chapter, we will cover the following topics:

  • Discovering method signature changes
  • Dealing with private methods
  • Working with interfaces and...

Technical requirements

To examine and run the code examples provided in this chapter, the minimum recommended hardware is as follows:

  • X86_64-based desktop PC or laptop
  • 1 GB free disk space
  • 4 GB of RAM
  • 500 Kbps or faster internet connection

In addition, you will need to install the following software:

  • Docker
  • Docker Compose

Please refer to the Technical requirements section of Chapter 1, Introducing New PHP 8 OOP Features, for more information on how to install Docker and Docker Compose, as well as how to build the Docker container used to demonstrate the code in this book. In this book, we will refer to the directory that you restored the sample code in as /repo.

The source code for this chapter is located here: https://github.com/PacktPublishing/PHP-8-Programming-Tips-Tricks-and-Best-Practices. We will start by examining significant method signature changes.

Discovering method signature changes

Several method signature changes have been introduced in PHP 8. Understanding these signature changes is important if your code extends any of the classes or implements any of the methods described in this section. As long as you are aware of these changes, your code will function correctly, resulting in fewer bugs.

The signature changes that were introduced in PHP 8 reflect the updated best practices. Accordingly, if you write code that uses the correct method signatures, you are following these best practices. We will begin our discussion by reviewing PHP 8 changes to magic method signatures.

Managing magic method signatures

In PHP 8, the definition and use of magic methods has taken a significant step toward standardization. This was accomplished by introducing precise magic method signatures in the form of strict argument and return data types. As with most of the improvements seen in PHP 8, this update was included to prevent the misuse...

Working with interfaces and traits

The PHP 8 trait implementation has been expanded in several ways. There are also several new interfaces that can potentially alter how you work with the DOM and DateTime extensions. For the most part, the changes improve the abilities of these two extensions. However, as method signatures have changed in some cases, you may run into a potential code break. Due to this, it's important to pay close attention to the discussion presented in this section to ensure that existing and future PHP code remains functional.

First, let's have a look at the new DOM extension interfaces.

Discovering new DOM extension interfaces

The cost of living economic statistic is issued each year by many world governments. It depicts how much it costs an average citizen to live year by year. As web technology matures, a similar principal has been applied – first to HTML, and now to DOM. The DOM Living Standard is maintained by the Web Hypertext Application...

Dealing with private methods

One of the reasons why developers create a super class is to exert a certain degree of control over the method signatures of subclasses. During the parsing phase, PHP normally confirms that the method signatures match. This leads to proper use of your code by other developers.

In the same vein, it does not make sense to have PHP perform the same rigorous method signature check if a method is marked as private. The purpose of a private method is that it is invisible to the extending class. If you define a method of the same name in the extending class, you should be free to define it at will.

To illustrate this problem, let's define a class called Cipher with a private method called encrypt(). The OpenCipher subclass redefines this method, causing a fatal error when running under PHP 7:

  1. First, let's define a Cipher class whose constructor generates random values for $key and $salt. It also defines a public method called encode() that...

Controlling anonymous class usage

Anonymous classes, by their very definition, do not have a name. However, for the purposes of information, PHP informational functions such as var_dump(), var_export(), get_class(), and other classes in the Reflection extension will report the anonymous class simply as class@anonymous. However, when an anonymous class extends another class or implements an interface, it might be of some use to have PHP informational functions reflect this fact.

In PHP 8, anonymous classes that extend a class or implement an interface now reflect that fact by changing the label that's assigned to the anonymous class to Xyz@anonymous, where Xyz is the name of the class or interface. If the anonymous class implements more than one interface, only the first interface will appear. If the anonymous class extends a class and also implements one or more interfaces, the name of the class it extends will appear in its label. The following table summarizes these possibilities...

Understanding changes in namespaces

The concept of a namespace was introduced in PHP 5.3 as a means of isolating hierarchies of classes. Unfortunately, the original algorithm that was used to parse namespace names had several flaws. In addition to being overly complicated, the way in which namespace and class names were tokenized internally was performed in an inconsistent manner, leading to unexpected errors.

Before we get into the benefits and potential backward compatible breaks, let's have a look at how the namespace tokenization process has changed.

Discovering differences in tokenization

The tokenization process is an important part of the interpretation process and takes place when your PHP code is executed. In the process of producing byte code, the PHP program code is broken down into tokens by the PHP parsing engine.

The following table summarizes namespace tokenization changes:

Table 9.5 – Namespace tokenization differences in...

Summary

PHP 8, as you learned, is much stricter in terms of how it defines magic methods. In this chapter, you learned about method signature changes and how to reduce potential bugs by using magic methods properly. You also learned about the method signature changes in both the Reflection and PDO extensions. With the knowledge you've gained in this chapter, you can avoid potential problems when migrating to PHP 8. In addition, you learned about changes in how static methods can be called, as well as a new static return type.

Then, you learned how to make the best use of private methods, as well as how to exert greater control over anonymous classes. You also picked up a few tips on new syntax possibilities and which methods are now obsolete due to changes in the language.

You also learned how to correctly use interfaces and traits to facilitate efficient use of your code. You learned about the new interfaces that were introduced to bring the DOM extension up to the new...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
PHP 8 Programming Tips, Tricks and Best Practices
Published in: Aug 2021Publisher: PacktISBN-13: 9781801071871
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Doug Bierer

Doug Bierer has been hooked on computers since his first program, written on a DEC PDP-8, in 1971. In his wide-ranging career, he has been a professional contract programmer since 1978, having written applications in BASIC, PL/I, assembler, FORTH, C, C++, dBase/FoxBase/Clipper, Pascal, Perl, Java, and PHP. He deployed his first website in 1993 while living in San Francisco. He speaks four languages, has traveled extensively, and now resides in Thailand. He also spent some years doing system administration and TCP/IP networking. Some of his technical works include PHP 7 Programming Cookbook and Learning MongoDB 4.x (Packt), as well as Learning PHP and MySQL, Learning PHP Security and Learning Doctrine (O'Reilly Media).
Read more about Doug Bierer