April 27, 2016

Time for PHP 7

From Rasmus Lerdorf’s Personal Home Page in 1994 through Zeev Suraski and Andi Gutmans’ rewritten parser for PHP in 1997, PHP has evolved much to occupy itself a prominent place in web development industry. Rasmus might not have thought his idea would become this giant tool. He hated programming and so decided to create a tool just to reuse the code. But later Suraski and Gutmans, the Israelites, worked with Rasmus for the public release PHP 3. PHP had gained momentum thereof and it didn’t take too much time to propagate inside the web development industry, sooner many frameworks and content management systems were released based on PHP.

For the production, PHP had released 3.0.x, 4.x.x, 5.x.x and support for PHP 4 and previous  versions had been discontinued since December 31, 2007.

Now, it’s PHP 7 not PHP 6!
PHP made releases constantly with feature additions. It was during June 11, 2015, PHP 7.0.0 Alpha 1 was released for experimental usage after PHP 5.6.10. After a debate, with votes favouring for PHP 7, the first alpha release was made. It was all because PHP 6 existed as an experimental project and was not moved to production phase. Many articles and books were released to support the migration of 5.x users to 6.x environment, in order to avoid disputes, version 7 was adopted.
It was on December 03, 2015 PHP development team announced the immediate availability of PHP 7.0.0 marking the start of the new major PHP 7 series.

Super powered engine
PHP 5.x had been powered with Zend Engine II. PHP 7.0.0 released with a new version of the Zend Engine - PHPNG (next generation) and numerous improvements. PHPNG’s significant performance improvement involves optimized memory usage that ultimately requires fewer servers for serving the same amount of users which previous versions had been serving for. With PHPNG, the code will be executed almost 2X faster.
Few benchmarks from Rasmus at Deploying PHP 7, Brooklyn, November 17, 2015. All statistics recorded with 20 requests per second and latency at 20.

1. Drupal 8-git



2. Wordpress 4.1.1



3. phpBB 3.1.3



4. MediaWiki 1.24.1


5. Wardrobe CMS 1.2.0


6. Moodle 2.9-dev


New Features and Additions
With the new release, many features have been introduced to support the programmers.

1.       Spaceship operator  [ <=> ]
Also called as combined comparison operator or three-way comparison operator used for comparing two operands of any type. It returns 0 when two operands are equal,  return 1 when the left operand is greater and returns -1 when the right operand is greater.

2.       Null coalescing operator [ ?? ]
            It is an improved ternary operation with addition of isset() to it. It returns its first operand if it exists and is not NULL, otherwise it returns its second operand.

3.       Anonymous classes
            It is a class without name, helpful for creating simple and one-off objects. Anonymous classes are extremely helpful when the class is used only once during an execution. It speeds up the execution time.

4.       Group use declarations
            Classes, functions and constants that are imported from the same namespace can be grouped together inside a single use statement. This makes the code cleaner and easier to read.
5.       Generator Improvements
            Generators are introduced in PHP 5.5 that yields as many values as it needs to instead of returning a value. In PHP 7 generator too can return values that can be fetched from new Generator::getReturn() method. In addition a generator can delegate to another generator

6.       Type declarations
            PHP 7 gives its developers, scalar and return type declaration. It is a quality enhancer for the code that adds a return type to the functions as scalar types int, float, string and bool with optional array type.

7.       Exception Handling improvements
            Now with PHP 7, error handling is also improved to support the developers to handle the exceptions appropriately instead of throwing some Fatal Errors.
a.       Throwable - Base interface for any object that can be thrown via a throw statement, including Error and Exception.
b.      Error - Base class for all internal PHP errors.
c.       ArithmeticError - Throws when performing mathematical operations.
d.      AssertionError - Thrown when an assertion made via assert() fails.
e.       DivisionByZeroError - Thrown when an attempt is made to divide a number by zero.
f.        ParseError - Thrown when an error occurs while parsing PHP code, such as when eval() is called.
g.       TypeError - Error related to functions for inappropriate arguments passed or return type doesn’t match with the one declared.

8.       Session options
            session_start() now accepts an array of options that override the session configuration directives normally set in php.ini.

9.       New Functions
            Out of many new functions, following are four of them that can be frequently used:
a.       intdiv() - Integer Division that returns the integer quotient of the division of dividend by divisor.
b.      random_bytes() - Generates cryptographically secure pseudo-random bytes
c.       random_int() - Generates cryptographically secure pseudo-random integers
d.      Generator::getReturn() - Get the return value of a generator (Generators in PHP 7 returns a value too)

Things to remember
While it is time for migration of old users into PHP 7, it is good to know that there are many deprecated functions dropped completely and many unwanted functions moved to deprecated list. This step is to clean up the garbage inside PHP! Be aware, while moving the legacy code to PHP 7 without prior steps, will break your system.

1.       To forget about:
a.       mysql_* functions
The entire mysql extension package has been removed from PHP 7 so adopt mysqli or PDO.
b.       asp_tags and script PHP tags
            Use only PHP tag.
2.       Time to start avoiding:
a.       PHP 4 style constructors
                        Usage of constructor with same name as class name is now deprecated
b.       Static calls to non-static methods
                        Static calls to methods that are not declared static are deprecated
c.       password_hash() salt option
Deprecated to prevent developers from generating their own (usually insecure) salts
3.       Have an eye on these:
a.       list()
                                                        i.    Assignment of values starts from left which was previously from right (from last). It is stated in their log not to depend on the order since this attempt is just implementation and can change in the future
                                                      ii.            Empty assignments have been removed
                                                    iii.            Cannot unpack string instead str_split() has to be used
b.       Array assignments with reference
The order of the elements in an array has changed when those elements have been automatically created by referencing them in a by reference assignment.
c.       global
Variable of variables can no longer be used with the global keyword. The curly brace syntax has to be used to emulate that behaviour
d.       foreach
                                                        i.            internal array pointer
Internal array pointer is maintained after iterating through foreach
                                                      ii.            iteration behaviour
When iterating by-reference, foreach will now do a better job of tracking changes to the array made during iteration. Which means values appended to the array inside the loop will also be tracked
4.       Suggestions for performance improvements
a.       Avoid using PHP end tag that prevents the unwanted whitespaces at the end of the file
b.       Avoid performing queries inside the loop
c.       Avoid using wildcards like * in SQL queries (instead use the appropriate column names) and wherever possible use SQL functions inside SQL query instead of PHP functions
d.       Never trust any user inputs, instead use filters before processing user inputs


Conclusion

PHP is not a dead language or not a “developed once and used now” language, it is under constant development supported by a vibrant open source community. With the new Zend engine - PHPNG, the performance of the latest release has rocketed up. Even in many test cases, it has bet its competitor HHVM. Definitely, PHP is immortal!


References