Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
PHP 7 Programming Cookbook
PHP 7 Programming Cookbook

PHP 7 Programming Cookbook: Over 80 recipes that will take your PHP 7 web development skills to the next level!

eBook
€8.99 €32.99
Paperback
€41.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

PHP 7 Programming Cookbook

Chapter 2. Using PHP 7 High Performance Features

In this chapter we will discuss and understand the syntax differences between PHP 5 and PHP 7, featuring the following recipes:

  • Understanding the abstract syntax tree
  • Understanding differences in parsing
  • Understanding differences in foreach() handling
  • Improving performance using PHP 7 enhancements
  • Iterating through a massive file
  • Uploading a spreadsheet into a database
  • Recursive directory iterator

Introduction

In this chapter we will move directly into PHP 7, presenting recipes that take advantage of new high performance features. First, however, we will present a series of smaller recipes that serve to illustrate the differences in how PHP 7 handles parameter parsing, syntax, a foreach() loop, and other enhancements. Before we go into depth in this chapter, let's discuss some basic differences between PHP 5 and PHP 7.

PHP 7 introduced a new layer referred to as the Abstract Syntax Tree (AST), which effectively decouples the parsing process from the pseudo-compile process. Although the new layer has little or no impact on performance, it gives the language a new uniformity of syntax, which was not possible previously.

Another benefit of AST is the process of dereferencing. Dereferencing, simply put, refers to the ability to immediately acquire a property from, or run a method of, an object, immediately access an array element, and immediately execute a callback. In PHP 5 such...

Understanding the abstract syntax tree

As a developer, it might be of interest for you to be free from certain syntax restrictions imposed in PHP 5 and earlier. Aside from the uniformity of the syntax mentioned previously, where you'll see the most improvement in syntax is the ability to call any return value, which is callable by simply appending an extra set of parentheses. Also, you'll be able to directly access any array element when the return value is an array.

How to do it...

  1. Any function or method that returns a callback can be immediately executed by simply appending parentheses () (with or without parameters). An element can be immediately dereferenced from any function or method that returns an array by simply indicating the element using square brackets [];. In the short (but trivial) example shown next, the function test() returns an array. The array contains six anonymous functions. $a has a value of $t. $$a is interpreted as $test:
    function test()
    {
        return [
     ...

Understanding differences in parsing

In PHP 5, expressions on the right side of an assignment operation were parsed right-to-left. In PHP 7, parsing is consistently left-to-right.

How to do it...

  1. A variable-variable is a way of indirectly referencing a value. In the following example, first $$foo is interpreted as ${$bar}. The final return value is thus the value of $bar instead of the direct value of $foo (which would be bar):
    $foo = 'bar';
    $bar = 'baz';
    echo $$foo; // returns  'baz'; 
  2. In the next example we have a variable-variable $$foo, which references a multi-dimensional array with a bar key and a baz sub-key:
    $foo = 'bar';
    $bar = ['bar' => ['baz' => 'bat']];
    // returns 'bat'
    echo $$foo['bar']['baz'];
  3. In PHP 5, parsing occurs right-to-left, which means the PHP engine would be looking for an $foo array, with a bar key and a baz. sub-key The return value of the element would then be interpreted...

Understanding differences in foreach() handling

In certain relatively obscure circumstances, the behavior of code inside a foreach() loop will vary between PHP 5 and PHP 7. First of all, there have been massive internal improvements, which means that in terms of sheer speed, processing inside the foreach() loop will be much faster running under PHP 7, compared with PHP 5. Problems that are noticed in PHP 5 include the use of current(), and unset() on the array inside the foreach() loop. Other problems have to do with passing values by reference while manipulating the array itself.

How to do it...

  1. Consider the following block of code:
    $a = [1, 2, 3];
    foreach ($a as $v) {
      printf("%2d\n", $v);
      unset($a[1]);
    }
  2. In both PHP 5 and 7, the output would appear as follows:
     1
     2
     3
  3. If you add an assignment before the loop, however, the behavior changes:
    $a = [1, 2, 3];
    $b = &$a;
    foreach ($a as $v) {
      printf("%2d\n", $v);
      unset($a[1]);
    }
  4. Compare the output of PHP 5 and 7:

    PHP...

Improving performance using PHP 7 enhancements

One trend that developers are taking advantage of is the use of anonymous functions. One classic problem, when dealing with anonymous functions, is to write them in such a way that any object can be bound to $this and the function will still work. The approach used in PHP 5 code is to use bindTo(). In PHP 7, a new method, call(), was added, which offers similar functionality, but vastly improved performance.

How to do it...

To take advantage of call(), execute an anonymous function in a lengthy loop. In this example, we will demonstrate an anonymous function, that scans through a log file, identifying IP addresses sorted by how frequently they appear:

  1. First, we define a Application\Web\Access class. In the constructor, we accept a filename as an argument. The log file is opened as an SplFileObject and assigned to $this->log:
    Namespace Application\Web;
    
    use Exception;
    use SplFileObject;
    class Access
    {
      const ERROR_UNABLE = 'ERROR: unable...

Iterating through a massive file

Functions such as file_get_contents() and file() are quick and easy to use however, owing to memory limitations, they quickly cause problems when dealing with massive files. The default setting for the php.ini memory_limit setting is 128 megabytes. Accordingly, any file larger than this will not be loaded.

Another consideration when parsing through massive files is how quickly does your function or class method produce output? When producing user output, for example, although it might at first glance seem better to accumulate output in an array. You would then output it all at once for improved efficiency. Unfortunately, this might have an adverse impact on the user experience. It might be better to create a generator, and use the yield keyword to produce immediate results.

How to do it...

As mentioned before, the file* functions (that is, file_get_contents()), are not suitable for large files. The simple reason is that these functions, at one point, have the...

Introduction


In this chapter we will move directly into PHP 7, presenting recipes that take advantage of new high performance features. First, however, we will present a series of smaller recipes that serve to illustrate the differences in how PHP 7 handles parameter parsing, syntax, a foreach() loop, and other enhancements. Before we go into depth in this chapter, let's discuss some basic differences between PHP 5 and PHP 7.

PHP 7 introduced a new layer referred to as the Abstract Syntax Tree (AST), which effectively decouples the parsing process from the pseudo-compile process. Although the new layer has little or no impact on performance, it gives the language a new uniformity of syntax, which was not possible previously.

Another benefit of AST is the process of dereferencing. Dereferencing, simply put, refers to the ability to immediately acquire a property from, or run a method of, an object, immediately access an array element, and immediately execute a callback. In PHP 5 such support...

Understanding the abstract syntax tree


As a developer, it might be of interest for you to be free from certain syntax restrictions imposed in PHP 5 and earlier. Aside from the uniformity of the syntax mentioned previously, where you'll see the most improvement in syntax is the ability to call any return value, which is callable by simply appending an extra set of parentheses. Also, you'll be able to directly access any array element when the return value is an array.

How to do it...

  1. Any function or method that returns a callback can be immediately executed by simply appending parentheses () (with or without parameters). An element can be immediately dereferenced from any function or method that returns an array by simply indicating the element using square brackets [];. In the short (but trivial) example shown next, the function test() returns an array. The array contains six anonymous functions. $a has a value of $t. $$a is interpreted as $test:

    function test()
    {
        return [
            1 =&gt...
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • This is the most up-to-date book in the market on PHP
  • It covers the new features of version 7.x, best practices for server-side programming, and MVC frameworks
  • The recipe-based approach will allow you to explore the unique capabilities that PHP offers to web programmers

Description

PHP 7 comes with a myriad of new features and great tools to optimize your code and make your code perform faster than in previous versions. Most importantly, it allows you to maintain high traffic on your websites with low-cost hardware and servers through a multithreading web server. This book demonstrates intermediate to advanced PHP techniques with a focus on PHP 7. Each recipe is designed to solve practical, real-world problems faced by PHP developers like yourself every day. We also cover new ways of writing PHP code made possible only in version 7. In addition, we discuss backward-compatibility breaks and give you plenty of guidance on when and where PHP 5 code needs to be changed to produce the correct results when running under PHP 7. This book also incorporates the latest PHP 7.x features. By the end of the book, you will be equipped with the tools and skills required to deliver efficient applications for your websites and enterprises.

Who is this book for?

If you are an aspiring web developer, mobile developer, or backend programmer, then this book is for you as it will take your PHP programming skills to next level. Basic knowledge of PHP programming is assumed.

What you will learn

  • Use advanced PHP 7 features, such as the Abstract Syntax Tree, Uniform Variable Syntax, Scalar Type Hints, Generator Delegation, Anonymous Classes, and the Context Sensitive Lexer
  • Discover where and when PHP 5 code needs to be re-written to avoid backwards-compatibility breaks
  • Improve the overall application security and error handling by taking advantage of classes that implement the new throwable interface
  • Solve practical real-world programming problems using PHP 7
  • Develop middle-wareclasses that allow PHP developers to gluedifferent open source libraries together seamlessly
  • Define and Implement PSR-7 classes
  • Create custom middleware using PSR-7 compliant classes
  • Test and debug your code, and get to know the best practices

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 30, 2016
Length: 610 pages
Edition : 1st
Language : English
ISBN-13 : 9781785882548
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Aug 30, 2016
Length: 610 pages
Edition : 1st
Language : English
ISBN-13 : 9781785882548
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total €26.97 €95.97 €69.00 saved
PHP 7 Programming Cookbook
€41.99
Learning PHP 7
€41.99
PHP 7 Data Structures and Algorithms
€36.99
Total €26.97€95.97 €69.00 saved Stars icon
Banner background image

Table of Contents

15 Chapters
1. Building a Foundation Chevron down icon Chevron up icon
2. Using PHP 7 High Performance Features Chevron down icon Chevron up icon
3. Working with PHP Functional Programming Chevron down icon Chevron up icon
4. Working with PHP Object-Oriented Programming Chevron down icon Chevron up icon
5. Interacting with a Database Chevron down icon Chevron up icon
6. Building Scalable Websites Chevron down icon Chevron up icon
7. Accessing Web Services Chevron down icon Chevron up icon
8. Working with Date/Time and International Aspects Chevron down icon Chevron up icon
9. Developing Middleware Chevron down icon Chevron up icon
10. Looking at Advanced Algorithms Chevron down icon Chevron up icon
11. Implementing Software Design Patterns Chevron down icon Chevron up icon
12. Improving Web Security Chevron down icon Chevron up icon
13. Best Practices, Testing, and Debugging Chevron down icon Chevron up icon
A. Defining PSR-7 Classes Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1
(8 Ratings)
5 star 62.5%
4 star 12.5%
3 star 0%
2 star 25%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




vikey89 Oct 17, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I was the Technical Reviewer on this book. It is focused on PHP 7, the latest version of PHP most likely the version with the highest performance.The book is clearly written, full of real examples that help the reader to understand the dynamics of the web. Also in the book it is included some fundamental Design Patterns for each developer.I recommend to read it.
Amazon Verified review Amazon
Amazon Customer Mar 26, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book will get you up to speed on PHP 7 through lots of very good code examples. A must-read for any developer that wants to unlock the benefits of using PHP 7!
Amazon Verified review Amazon
thomas Oct 27, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Super reference for php 7.x
Amazon Verified review Amazon
Shawn Flock Apr 18, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great book if you start on page 53. The beginning is a tad bit confusing. But if you pick and chose what you want to learn about or start at chapter 3 it is phenomenal. Straight, to the point, with lots and lots of information.
Amazon Verified review Amazon
Salvatore Pappalardo Sep 11, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I've known Doug for long time and I was happy to have had the opportunityto review his last PHP book especially because it is focused on PHP7, oneof PHP version with the most impressive performance increase of ever and alot of brand new nice features.I liked so much the pragmatic approach of the book and the "learn byexample" style of all chapters, because it allows to understand immediatelynot only why a feature was introduced but also how to use it efficiently inreal and common problems of a developer life.Among all, I've appreciated mainly chapters about common advancedalgorithms and most used design patterns, both explained very well andsimple.Definitely recommended!
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.