PHP 8 Programming Tips, Tricks and Best Practices

Book description

Discover effective techniques, workarounds, and expert guidance for avoiding situations where your application might break following PHP 8 migration

Key Features

  • Get the hang of all the new features introduced in PHP 8
  • Learn how to detect potential code breaks and keep your application code running smoothly in PHP 8
  • Explore an exciting new trend - asynchronous PHP programming using Swoole and Fibers

Book Description

Thanks to its ease of use, PHP is a highly popular programming language used on over 78% of all web servers connected to the Internet. PHP 8 Programming Tips, Tricks, and Best Practices will help you to get up-to-speed with PHP 8 quickly. The book is intended for any PHP developer who wants to become familiar with the cool new features available in PHP 8, and covers areas where developers might experience backward compatibility issues with their existing code after a PHP 8 update. The book thoroughly explores best practices, and highlights ways in which PHP 8 enforces these practices in a much more rigorous fashion than its earlier versions.

You'll start by exploring new PHP 8 features in the area of object-oriented programming (OOP), followed by enhancements at the procedural level. You'll then learn about potential backward compatible breaks and discover best practices for improving performance. The last chapter of the book gives you insights into PHP async, a revolutionary new way of programming, by providing detailed coverage and examples of asynchronous programming using the Swoole extension and Fibers.

By the end of this PHP book, you'll not only have mastered the new features, but you'll also know exactly what to watch out for when migrating older PHP applications to PHP 8.

What you will learn

  • Gain a comprehensive understanding of the new PHP 8 object-oriented features
  • Discover new PHP 8 procedural programming enhancements
  • Understand improvements in error handling in PHP 8
  • Identify potential backward compatibility issues
  • Avoid traps due to changes in PHP extensions
  • Find out which features have been deprecated and/or removed in PHP 8
  • Become well-versed with programming best practices enforced by PHP 8

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 the language. 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.

Table of contents

  1. PHP 8 Programming Tips, Tricks and Best Practices
  2. Foreword
  3. Contributors
  4. About the author
  5. About the reviewer
  6. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
    4. Download the example code files
    5. Download the color images
    6. Conventions used
    7. Get in touch
    8. Share Your Thoughts
  7. Section 1: PHP 8 Tips
  8. Chapter 1: Introducing New PHP 8 OOP Features
    1. Technical requirements
    2. Using constructor property promotion
      1. Property promotion syntax
      2. Using property promotion for code reduction
    3. Working with attributes
      1. Overview of PHP comments
      2. PHP DocBlock considerations
      3. Hidden dangers associated with the misuse of DocBlocks
      4. The Attribute class
      5. Attribute syntax
    4. Incorporating match expressions into your program code
      1. Match expression general syntax
    5. Understanding named arguments
      1. Named argument generic syntax
      2. Calling core functions using named arguments
      3. Order independence and documentation
    6. Exploring new data types
      1. Union types
      2. mixed type
      3. The effect of a mixed type on inheritance
    7. Improving code using typed properties
      1. What are typed properties?
      2. Property typing can lead to a reduction in code
    8. Summary
  9. Chapter 2: Learning about PHP 8's Functional Additions
    1. Technical requirements
    2. Working with new PHP 8 operators
      1. Using the variadics operator
      2. Using the nullsafe operator
      3. The concatenation operator has been demoted
      4. Using nested ternary operators
    3. Using arrow functions
      1. Generic syntax
      2. Arrow functions versus anonymous functions
      3. Variable inheritance
      4. Practical example: Using arrow functions
    4. Understanding uniform variable syntax
      1. Defining uniform variable syntax
      2. How does uniform variable syntax affect PHP 8?
    5. Learning new array- and string-handling techniques
      1. Working with array_splice()
      2. Using array_slice()
      3. Detecting string beginning, middle, and end
    6. Securing SQLite databases with the authorizer
      1. Wait a minute... no security?
      2. What's a SQLite authorization callback?
      3. What gets sent to the callback?
      4. Authorizer usage example
    7. Summary
  10. Chapter 3: Taking Advantage of Error-Handling Enhancements
    1. Technical requirements
    2. Understanding PHP 8 error handling
      1. Undefined variable handling
      2. Undefined constant handling
      3. Error-level defaults
    3. Dealing with warnings that are now errors
      1. Promoted warnings in object error handling
      2. Promoted warnings in array handling
      3. Promoted warnings in string handling
    4. Understanding notices promoted to warnings
      1. Non-existent object property access handling
      2. Non-existent offset handling
      3. Misusing resource IDs as array offsets
      4. Ambiguous string offset cast
      5. Uninitialized or non-existent string offsets
    5. Handling the @ error control operator
      1. @ operator usage
      2. @ operator and error_reporting()
    6. Summary
  11. Chapter 4: Making Direct C-Language Calls
    1. Technical requirements
    2. Understanding FFI
      1. Relationship between PHP and the C language
      2. Understanding PHP extensions
    3. Learning where to use FFI
      1. Adopting FFI into PHP
      2. Do not use FFI for speed
      3. Why use the FFI extension?
    4. Examining the FFI class
      1. Working with FFI creational methods
      2. Comparing data using FFI
      3. Using FFI infrastructural methods
    5. Using FFI in an application
      1. Integrating an external C library into a PHP script
      2. Working with PHP callbacks
    6. Summary
  12. Section 2: PHP 8 Tricks
  13. Chapter 5: Discovering Potential OOP Backward-Compatibility Breaks
    1. Technical requirements
    2. Discovering core OOP coding differences
      1. Handling static calls in PHP 8
      2. Dealing with object property handling changes
      3. Working with PHP 8 autoloading
    3. Navigating changes in magic methods
      1. Dealing with constructor changes
      2. Working with changes to __toString()
    4. Taking control of serialization
      1. Understanding PHP serialization
      2. Understanding the __sleep() magic method
      3. Understanding a potential code break in the __sleep() method
      4. Learning about __wakeup()
      5. Introducing the Serializable interface
      6. Examining PHP serializable interface issues
      7. New magic methods to control PHP serialization
    5. Understanding PHP 8 expanded variance support
      1. Understanding covariant returns
      2. Using contravariant parameters
    6. Handling Standard PHP Library (SPL) changes
      1. Understanding changes to SplFileObject
      2. Examining changes to SplHeap
      3. Handling changes in SplDoublyLinkedList
    7. Summary
  14. Chapter 6: Understanding PHP 8 Functional Differences
    1. Technical requirements
    2. Learning key advanced string handling differences
      1. Handling changes to the needle argument
      2. Dealing with v*printf() changes
      3. Working with null length arguments in PHP 8
      4. Examining changes to implode()
      5. Learning about constants usage in PHP 8
    3. Understanding PHP 8 string-to-numeric comparison improvements
      1. Learning about strict and non-strict comparisons
      2. Examining numeric strings
      3. Detecting backward-compatible breaks involving numeric strings
      4. Dealing with inconsistent string-to-numeric comparison results
      5. Understanding comparison changes made in PHP 8
      6. Avoiding problems during a PHP 8 upgrade
    4. Handling differences in arithmetic, bitwise, and concatenation operations
      1. Handling non-scalar data types in arithmetic and bitwise operations
      2. Examining changes in the order of precedence
    5. Taking advantage of locale independence
      1. Understanding the problems associated with locale dependence
      2. Reviewing functions and operations affected by locale independence
    6. Handling arrays in PHP 8
      1. Dealing with negative offsets
      2. Handling curly brace usage changes
    7. Mastering changes in security functions and settings
      1. Understanding changes in disabled functions handling
      2. Learning about changes to the crypt() function
      3. Dealing with changes to password_hash()
      4. Learning about changes to assert()
    8. Summary
  15. Chapter 7: Avoiding Traps When Using PHP 8 Extensions
    1. Technical requirements
    2. Understanding the shift from resources to objects
      1. PHP 8 extension resource-to-object migration
      2. Potential code break involving is_resource()
      3. Advantages of objects over resources
      4. Traversable to IteratorAggregate migration
    3. Learning about changes to XML extensions
      1. Examining XMLWriter extension differences
      2. Working with changes to the SimpleXML extension
      3. Understanding other XML extension changes
    4. Avoiding problems with the updated mbstring extension
      1. Discovering needle-argument differences in mb_str*() functions
      2. Examining changes to mb_ereg*() functions
    5. Dealing with changes to the GD extension
      1. GD extension resource-to-object migration
      2. GD extension compile flag changes
      3. Other GD extension changes
    6. Discovering changes to the Reflection extension
      1. Reflection extension usage
      2. Learning about Reflection extension improvements
    7. Working with other extension gotchas
      1. New database extension operating system library requirements
      2. Reviewing changes to the ZIP extension
      3. Examining PCRE extension changes
      4. Working with Intl extension changes
      5. Understanding cURL extension changes
      6. Reviewing COM extension changes
      7. Examining other extension changes
    8. Summary
  16. Chapter 8: Learning about PHP 8's Deprecated or Removed Functionality
    1. Technical requirements
    2. Discovering what has been removed from the core
      1. Examining functions removed in PHP 8
      2. Discovering other PHP 8 usage changes
    3. Examining core deprecations
      1. Deprecated usage in parameter order
    4. Working with removed functionality in PHP 8 extensions
      1. Discovering mbstring extension changes
      2. Reworking code that uses Reflection*::export()
      3. Discovering other deprecated PHP 8 extension functionality
      4. Changes to the XML-RPC extension
      5. Changes made to the DOM extension
    5. Dealing with deprecated or removed security-related functionality
      1. Examining PHP 8 stream-filter changes
      2. Dealing with custom error-handling changes
      3. Dealing with changes to backtraces
      4. PDO error-handling mode default changed
      5. Examining the track_errors php.ini setting
    6. Summary
  17. Section 3: PHP 8 Best Practices
  18. Chapter 9: Mastering PHP 8 Best Practices
    1. Technical requirements
    2. Discovering method signature changes
      1. Managing magic method signatures
      2. Examining Reflection method signature changes
      3. Dealing with PDO extension signature changes
      4. Dealing with newly defined static methods
      5. Working with the static return type
      6. Extending the use of the ::class constant
      7. Taking advantage of trailing commas
      8. Learning about methods that are no longer required
    3. Working with interfaces and traits
      1. Discovering new DOM extension interfaces
      2. Using new DateTime methods
      3. Understanding PHP 8 trait handling refinements
    4. Dealing with private methods
    5. Controlling anonymous class usage
    6. Understanding changes in namespaces
      1. Discovering differences in tokenization
      2. Using reserved keywords in a namespace
      3. Exposing bad namespace naming practices
    7. Summary
  19. Chapter 10: Improving Performance
    1. Technical requirements
    2. Working with the JIT compiler
      1. Discovering how PHP works without JIT
      2. Enabling the JIT compiler
      3. Configuring the tracing mode
      4. Using the JIT compiler
      5. Debugging with the JIT compiler
      6. Discovering additional JIT compiler settings
    3. Speeding up array handling
      1. Working with SplFixedArray in PHP 8
    4. Implementing stable sort
      1. Understanding stable sorts
      2. Contrasting stable and non-stable sorting
      3. Examining the effect of stable sorting on keys
      4. Handling illegal sort functions
    5. Using weak references to improve efficiency
      1. Taking advantage of weak references
      2. Reviewing the WeakReference class definition
      3. Using weak references
      4. Working with WeakMap
      5. Implementing a container class using SplObjectStorage
      6. Understanding the benefits of WeakMap over SplObjectStorage
    6. Summary
  20. Chapter 11: Migrating Existing PHP Apps to PHP 8
    1. Technical requirements
    2. Understanding development, staging, and production environments
      1. Defining an environment
    3. Learning how to spot BC breaks before a migration
      1. Gaining an overview of BC breaks
      2. Creating a BC break scan configuration file
      3. Developing a BC break scan class
    4. Performing the migration
      1. Step 1 – Review the migration guide
      2. Step 2 – Make sure the current code works
      3. Step 3 – Back up everything
      4. Step 4 – Create a version control branch
      5. Step 5 – Scan for BC breaks
      6. Step 6 – Fix incompatibilities
      7. Step 7 – Repeat steps 5 and 6 as needed
      8. Step 8 – Commit changes to the repository
      9. Step 9 – Test in a simulated virtual environment
      10. Step 10 – Return to step 5 if the test is unsuccessful
      11. Step 11 – Install PHP 8 on the staging environment
      12. Step 12 – Test and clone the staging environment to production
    5. Testing and troubleshooting the migration
      1. Testing and troubleshooting tools
      2. Handling issues with Composer
      3. Working with unit tests
    6. Summary
  21. Chapter 12: Creating PHP 8 Applications Using Asynchronous Programming
    1. Technical requirements
    2. Understanding the PHP async programming model
      1. Developing synchronous programming code
      2. Understanding the asynchronous programming model
      3. Working with async coroutine support
      4. Creating a PHP async application
    3. Using the Swoole extension
      1. Examining the Swoole extension
      2. Installing the Swoole extension
      3. Testing the installation
      4. Examining a sample I/O-intensive application
      5. Using the Swoole extension to improve application performance
    4. Using selected PHP frameworks in async mode
      1. Working with ReactPHP
      2. Implementing PHP async using Amp
      3. Using Mezzio with Swoole
      4. Working with the parallel extension
    5. Learning about PHP 8.1 fibers
      1. Discovering the Fiber class
      2. Using fibers
      3. Examining the effect of fibers on ReactPHP and Swoole
    6. Summary
    7. Why subscribe?
  22. Other Books You May Enjoy
    1. Packt is searching for authors like you
    2. Share Your Thoughts

Product information

  • Title: PHP 8 Programming Tips, Tricks and Best Practices
  • Author(s): Doug Bierer
  • Release date: August 2021
  • Publisher(s): Packt Publishing
  • ISBN: 9781801071871