Preface

PHP 8 represents the culmination of the PHP core development team's work to maximize efficiency in the core language. Your application code will immediately see a boost in speed as well as having a smaller memory footprint just by migrating to PHP 8. Further, in PHP 8, developers notice that a tremendous effort has gone into normalizing syntax and language usage. In short, programming in PHP 8 is a joy to developers who appreciate adherence to good coding practices.

However, this inevitably leads to the question: where does the PHP language go from here? PHP 8 provides the answer to this question as well, in the form of the Just-In-Time compiler and support for fibers. The latter forms the foundation of asynchronous programming and has been announced for PHP 8.1. PHP 8 gives you a glimpse of the future of the language, and that future is looking extremely bright!

If you put all this together, it becomes clear that understanding and mastering the new features and stricter coding practices implemented in PHP 8 is vital to those who wish to pursue a serious career as a PHP developer. This book is exactly the tool you need to get up and running with PHP 8 quickly. Not only do we cover new features, but we also show you how to avoid traps that could lead to code failure after a PHP 8 migration. In addition, we give you a glimpse into the future of PHP via thorough coverage of the JIT compiler and PHP asynchronous programming.

Who this book is for

This book is for PHP developers at all levels who have experience in PHP 5 or above. If you're just getting started with PHP, you'll find the code examples useful for learning to use the language more effectively. Developers who have worked for a few months on one or more PHP projects will be able to apply the tips and techniques to the code at hand, while those with many years of PHP experience are sure to appreciate the concise coverage of new PHP 8 features.

What this book covers

Chapter 1, Introducing New PHP 8 OOP Features, introduces you to new PHP 8 features specific to Object-Oriented Programming (OOP). The chapter features plenty of short code examples that clearly illustrate the new features and concepts. This chapter is critical in helping you quickly take advantage of the power of PHP 8 and adapt the code examples to your own practice.

Chapter 2, Learning about PHP 8's Functional Additions, covers important additions and enhancements introduced to PHP 8 at the procedural level. It includes plenty of code examples that show new PHP 8 features and techniques to facilitate procedural programming. This chapter teaches you how to write faster and cleaner application code.

Chapter 3, Taking Advantage of Error-Handling Enhancements, explores one of the key improvements in PHP 8, its advanced error handling capabilities. In this chapter, you learn which Notices have been upgraded to Warnings, as well as which Warnings have now been promoted to Errors. This chapter will give you an excellent understanding of the background and intent of security enhancements allowing you to better control the use of your code. In addition, it's critical to be aware of error conditions that formerly only generated Warnings, but now generate Errors, so that you take measures to prevent your applications from failing following an upgrade to PHP 8.

Chapter 4, Making Direct C-Language Calls, helps you to learn what the Foreign Function Interface (FFI) is all about, what it's good for, and how to use it. The information in this chapter is important for developers interested in rapid custom prototyping using direct C language calls. This chapter shows you how to incorporate C language structures and functions directly into your code, opening the doors to an entire world of functionality hitherto unavailable to PHP.

Chapter 5, Discovering Potential OOP Backward-Compatibility Breaks, introduces you to new PHP 8 features specific to OOP. The chapter features plenty of short code examples that clearly illustrate the new features and concepts. This chapter is critical in helping you quickly take advantage of the power of PHP 8 by adapting the code examples into your own practice. In addition, this chapter highlights situations where object-oriented code might break after a PHP 8 migration.

Chapter 6, Understanding PHP 8 Functional Differences, covers potential backwards d-compatibility breaks at the PHP 8 command or functional level. This chapter presents important information that highlights potential pitfalls when migrating existing code to PHP 8. The information presented in this chapter enables you to produce reliable PHP code. After working through the concepts in this chapter, you'll be in a better position to write code that produces precise results and avoids inconsistencies.

Chapter 7, Avoiding Traps When Using PHP 8 Extensions, takes you through the major changes to extensions that have been made and how to avoid traps when updating an existing application to PHP 8. Once you finish reviewing the sample code and topics presented, you'll be able to prepare any existing PHP code for migration to PHP 8. In addition to learning about the changes to the various extensions, you'll also gain deep insight into their operation. This will allow you to make informed decisions when using extensions in PHP 8.

Chapter 8, Learning about PHP 8's Deprecated or Removed Functionality, walks you through functionality that has been deprecated or removed in PHP 8. After you have read the material in this chapter and followed the example application code, you will be able to detect and rewrite code that has been deprecated. You will also learn how to develop workarounds for functionality that has been removed as well as how to refactor code that uses removed functionality involving extensions. Another important skill you will learn in this chapter is how to improve application security by rewriting code depending on functions that have been entirely removed in PHP 8.

Chapter 9, Mastering PHP 8 Best Practices, introduces you to best practices now enforced in PHP 8. It covers a number of significant method signature changes and how their new usage continues the general PHP trend of helping you to produce better code. You will also learn about changes in the use of private methods, interfaces, traits, and anonymous classes, and how namespaces are now parsed. Mastering the best practices covered in this chapter will not only move you toward writing better code but will help you avoid the potential code breaks that might arise if you fail to grasp these new practices.

Chapter 10, Improving Performance, introduces you to a number of new PHP 8 features that have a positive effect on performance, with a special focus on the new Just-In-Time compiler. This chapter also includes thorough coverage of weak references whose proper use results in applications that use far less memory. By carefully reviewing the material covered in this chapter and by studying the code examples, you will be able to write faster and more efficient code.

Chapter 11, Migrating Existing PHP Apps to PHP 8, introduces a set of classes that form the basis of a PHP 8 backward-compatible break scanner. Throughout the book, you are shown potential code breaks that might follow a PHP 8 update. In addition, you will learn about the recommended process for migrating an existing customer PHP application to PHP 8. This chapter will leave you much better equipped to handle a PHP 8 migration, giving you the ability to perform PHP 8 migrations with greater confidence and a minimum number of problems.

Chapter 12, Creating PHP 8 Applications Using Asynchronous Programming, explains the difference between the traditional synchronous and asynchronous programming models. In recent years, an exciting new technology has taken the PHP community by storm: asynchronous programming, also known as PHP async. In addition, popular PHP async extensions and frameworks, including the Swoole extension and ReactPHP are covered, with plenty of examples to get you started. By the time you are done working through this chapter, you will be in a position to improve the performance of your applications, making them anywhere from 5 times up to a staggering 40 times faster!

To get the most out of this book

To get the most out of this book, you must have a basic understanding of PHP syntax, variables, control structures (for example, if {} else {}), looping structures (for example, for () {}), arrays, and functions. You must also have a basic idea of PHP OOP: classes, inheritance, and namespaces.

If you have not received formal PHP training, or are unsure that you have the necessary knowledge, please review these two sections of the online PHP reference manual:

Here is a summary of the software covered in this book:

Note

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book's GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/PHP-8-Programming-Tips-Tricks-and-Best-Practices. If there's an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781801071871_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "This chapter also taught you how the new Attribute class can be used as an eventual replacement for PHP DocBlocks."

A block of code is set as follows:

// /repo/ch01/php7_prop_reduce.php

declare(strict_types=1);

class Test {

protected $id = 0;

protected $token = 0;

protected $name = '';o

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

$result = match(<EXPRESSION>) {

    <ITEM> => <EXPRESSION>,

   [<ITEM> => <EXPRESSION>,]

    default => <DEFAULT EXPRESSION>

};

Any command-line input or output is written as follows:

Fatal error: Uncaught TypeError: Cannot assign string to property Test::$token of type int in /repo/ch01/php8_prop_danger.php:12

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Once you've read PHP 8 Programming Tips, Tricks and Best Practices, we'd love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we're delivering excellent quality content.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.190.167