New features in PHP 7

Soft Landing

© Lead Image © joingate, 123RF.com

© Lead Image © joingate, 123RF.com

Article from Issue 184/2016
Author(s):

How will developers have to change their PHP 5 scripts to conform to the new PHP 7? We look at some of the important changes.

PHP 7 [1] was just released at the end of 2015 and updated to version 7.0.2 early in January 2016. In addition to providing 64-bit support throughout, the new major release of the scripting language gets rid of a variety of ugly hacks. The "PHP 7 Install" box describes the installation of stable version 7.0.2.

PHP 7 Install

If your distribution does not offer PHP 7 in its repositories, in Debian distros, you can obtain a version of PHP 7.0.2 and install it in your home directory – supported by the command-line switches --prefix and --with-config-file-path – by entering the commands in Listing 1. You then need to add the export PATH=$PATH:$HOME/php7-02/usr/bin expression to the end of the ~/.bashrc file. Finally, create a symbolic link for the PHP binary:

cd ~/php7-02/usr/bin/
ln -s php php7

After restarting the shell, you can start PHP 7 by entering php (Figure 1).

Figure 1: PHP 7 is pretty easy to install and set up on Debian 8.

Listing 1

Installing PHP 7 in Debian 8

 

Coming to Terms with the Past

The PHP 7 developers managed to increase the expressiveness of their linguistic resources by revising historical defects – at the expense of losing backward compatibility. However, it isn't necessarily the smaller changes that are responsible for the troubles. For example, PHP 7 might only still allow one default clause per switch instruction and prohibit the same function parameters as in:

function foo($value, $ignored, $ignored)

However, such expressions have always been taboo for PHP users anyway. Before the release of PHP 7, the makers of PHP also advised their users to avoid the keywords bool, int, float, string, zero, true, and false as names for classes, traits, and interfaces.

However, originally there were no objections to ASP tags such as <% [...] %>, <= [...] => and <script language="php"> [...] </script>, which developers typically use to localize PHP code. Now anyone using these tags needs to brace themselves for some work and replace the tags with <?php [...] > after changing to version 7.

Additionally, PHP 7 now throws exceptions and has completely dropped the E_STRICT error level. However, because it articulates a variety of error messages, PHP 5 applications might react completely differently than expected when run under PHP 7, particularly if your application uses its own error handlers. Developers are forced to comb through the source code in such cases.

Clarification Process

Programmers using indirect variables probably also need to revise their code for each case because, logically, PHP still evaluates the $$foo['ref'] expression as the $($foo['ref']) pseudo-expression. However, PHP 7 interprets it approximately as $($foo)['ref'] because the dereferencing operator $ works strictly from left to right in the new major release (Figure 2). Line 5 from Listing 2 therefore outputs the character string foo.

Figure 2: PHP 7 puts together the word foobar in Listing 2.

Listing 2

Expanding indirect variables

 

If you use curly brackets, you can control this expansion and restore the behavior of PHP 5 by making a smart choice, as in line 6, which returns the character string bar. If you want to run the listings in PHP 7, you need to quote the code, as in <?php [...] ?>. Otherwise, PHP won't recognize it and will just display the source code.

The foreach loop also treats variables in PHP 7 slightly differently. When the scripting language iterates over a field, the changes that occur within the loop body do not necessarily affect the field (Listing 3), because PHP 7 iterates over a copy of the $arr field in line 2. Thus, deleting the second field element by means of unset($arr[1]) (line 6) has no effect. The script returns the values 1, 2, and 3 in the shell (Figure 3, left).

Listing 3

Iterations remain undamaged

 

Figure 3: Left: PHP 7 default behavior; iterating over a copy of the $arr field. Right: backward compatibility with PHP 5; iterating over the actual $arr field by using the & character.

As before, backward compatibility with PHP 5 can be restored. If you want the code to iterate directly over the field from line 2, you need to insert the & reference operator in front of the var control variable in the header of the loop:

foreach ($arr as &$var)

PHP 7 displays the values 1 and 3 as a result (Figure 3, right). Unlike PHP 5, the new version doesn't increment the field pointer from a foreach loop; therefore, calling the current() function, which returns the value of the array element being pointed to, will always return the same value.

The developers eliminated a prominent side effect by indexing fields. The order of a field remains literal in PHP 7 if the script links a field using a reference with the value of a following key-value pair (Listing 4, line 3). The last line would swap 'a' and 'b' in

array (2) {[" a "] =>   &int (0) [" b "] => &int (0)}

under PHP 5.

Listing 4

Purely Literal

 

Cultivation

The repairs to the list construct were also well overdue. The expression

list($a[], $a[], $a[]) = array(1,2,3);

now stores the numbers from the field to the right of the equals sign in $a in the correct ascending order: 1, 2, 3. Moreover, list breaks down all objects whose template classes implement the array access interface, such as:

list($a, $b) = (object) new ArrayObject([0, 1])

However, PHP 7 no longer extracts character strings from variables, and empty list expressions such as list() = $a; also issue an error.

PHP 7 also handles data types differently. Illegal expressions for octal numbers like 0128 now trigger a parser error, and bit-shift operations with negative numbers (e.g., 1 >> -1 ) throw an ArithmeticError exception.

PHP 7 always interprets bit-shift operations whose results exceed the width of one integer as 0. Previously, the result of such operations was fatally dependent on the processor architecture being used. PHP 7 also reacts differently to dividing by 0. It no longer interprets hexadecimal numbers within character strings and the '0xf' == 0xf expression as always wrong.

If you're still wondering why your PHP scripts aren't working, you should take a look at the list of changed features [2]. For the sake of completeness, it should be noted that double brackets around return values from functions are now only formally redundant and that global only accepts simple variables.

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Linux Magazine

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

  • Rust Language

    We look at a few features of Rust, Mozilla's systems programming language, and its similarity to other languages.

  • ECMAScript 6

    The new ECMAScript 6 language eliminates many historical problems associated with JavaScript.

  • Dotnet Scripting with Boo

    Boo is a scripting language tailor-made for Mono and .NET. This haunting mixture of Python and C# may be just what you need to get started with the .NET framework.

  • Python generators simulate gambling

    Can 10 heads in a row really occur in a coin toss? Or, can the lucky numbers in the lottery be 1, 2, 3, 4, 5, 6? We investigate the law of large numbers.

  • Pony Programming Language

    Pony, an object-oriented programming language with static typecasting, trots down well-mapped paths to deliver secure, high-performance code for concurrent applications.

comments powered by Disqus
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs
Subscribe to our ADMIN Newsletters

Support Our Work

Linux Magazine content is made possible with support from readers like you. Please consider contributing when you’ve found an article to be beneficial.

Learn More

News