DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

  1. DZone
  2. Refcards
  3. PHP 5.5 & 5.6
refcard cover
Refcard #205

PHP 5.5 & 5.6

What's New in PHP

Covers new improvements and platform enhancements in the 5.5 and 5.6 releases of this server-side scripting language.

Download Refcard
Free PDF for Easy Reference
refcard cover

Written By

author avatar Luis Atencio
Staff Software Engineer, Citrix Systems
Table of Contents
► About ► New in 5.5 ► PHP 5.5 Platform Enhancements ► PHP 5.5 Incompatibilities ► PHP 5.6 Incompatibilities ► Conclusion
Section 1

About

PHP is a server-side scripting language designed for the development of web applications. With its concise syntax, rich function library, and powerful language constructs, PHP continues to be the platform of choice amongst web developers at large. It’s no surprise that PHP powers around 240+ million sites. Each new release of PHP brings new innovations and enhancements. While the road to PHP6 continues to be a delusion, the 5.5 and 5.6 releases have added numerous enhancements to the core and new language features, but also introduced a few backward incompatibilities that are worth considering.

New in 5.5

New features added in 5.5 include support for generators, the finally keyword, password hashing APIs, a new list construct, array and string literal dereferencing, and more. For a list of these features, visit http://php.net/manual/en/migration55. new-features.php.

New in 5.6

PHP 5.6 adds support for constant scalar expressions, variadic functions, argument unpacking, and changes to the use keyword, among many others. For a list of these features, visit http://php.net/manual/en/migration56.new-features.php.

Incompatibilities

Some backward incompatibilities were also introduced to the platform, which means developers should take caution when upgrading PHP to either version.

Section 2

New in 5.5

The 5.5 release comes bundled with a number of new features.

Generators

The general foreach statement in PHP looks like the following:

​x
1
​
2
   foreach($collection as $item) {
3
// process item }
4
​
5
​

This works for arrays and iterators containing efficiently small data sets since all data is stored in memory. For larger data sets, we need another solution.

A generator is a special function used to augment the iteration behavior of a loop statement. In basic terms, generators are similar to functions that return an array or sequence of values; instead of returning all values at once, generators return values one at a time, thereby utilizing less memory and processing time. This is a very powerful language feature that has been present in other languages, such as Python, for quite some time. And now it’s being added to PHP.

Generators are very closely linked to iterators. Iterators are a language construct available in PHP via the SPL library and the Iterator interface.

Iterators

Added in 5.0, the Iterator interface can be used to create custom external iterators. A class is considered iterable if it extends the following interface:

Embedding an instance of this class in a foreach() will treat it as if it were a collection, so long as the valid() and next() calls continue producing valid results.

The latest versions of PHP5+ take advantage of this and provide a variety of canned iterators to choose from via the SPL library. For more information on SPL iterators, please visit http://php.net/manual/en/spl.iterators.php.

For more information on iterators in general, visit http://php. net/manual/en/class.iterator.php.

Generators

Generators provide yet another alternative when creating simple iterators without having to implement any interfaces.

Similar to iterators, generators allow developers to write code that leverages foreach()to traverse a set of data in both a memory and processing-efficient manner. Instead of traversing elements all at once, generator functions take advantage of the yield keyword to produce results as many times as needed to provide the value set being iterated over. The presence of yield turns any function into a generator. Behind the scenes, PHP will save the state of the generator when it yields a value so that it can be “woken up” next time a value is required.

When a generator function is called, an instance of the Generator class is returned. Behind the scenes, this class implements the Iterator interface previously discussed and adds 3 methods:

8
1
​
2
   Generator implements Iterator {
3
public mixed send ( mixed $value )
4
public mixed throw ( Exception $exception ) public void __wakeup ( void )
5
}
6
​
7
​
8
​

These methods allow generators internally to save its state and resume where it left off next time it’s called.

The PHP range($start, $end, [, number $step = 1]) function is used to generate an array of values with every element in it from start to end parameters inclusively, separated by the step value.

6
1
​
2
   foreach (range(0, 100000) as $number) {
3
echo $number; }
4
​
5
​
6
​

This statement will create an array of 100001 elements (including 0), loop over all of them and print each one. Understandably, the performance of the range function is degraded as the end value becomes bigger. Generators can be used to implement range() much more effectively. Let’s call it xrange($start, $end, [, number $step = 1]).

12
1
​
2
   function xrange($start, $limit, $step = 1) {
3
    if ($start < $limit) {
4
for ($i = $start; $i <= $limit; $i += $step) {
5
yield $i; }
6
} else {
7
for ($i = $start; $i >= $limit; $i += $step) {
8
yield $i; }
9
} }
10
​
11
​
12
​

Generator functions return a Generator instance, which we can place inside of a foreach statement and iterate over a range of elements without ever needing additional memory.

6
1
​
2
   foreach (xrange(0, 100000) as $number) {
3
echo $number; }
4
​
5
​
6
​

Let’s look at simplifying another task done on a daily basis where generators can play a significant role, file I/O:

13
1
​
2
   Let’s look at simplifying another task done on a daily basis where generators can play a significant role, file I/O:
3
function readLinesFrom($filename) {
4
$fh = fopen($filename, ‘r’);
5
if (!$fh)
6
throw new Exception(‘Error opening file ’.
7
$filename);
8
while (($line = fgets($fh)) !== false)
9
yield $line; }
10
fclose($fh); }
11
​
12
​
13
​

This function can be used to read lines from a text file. The important statement in this code is the loop. As lines are read, the generator function yields each line one at a time, starting where it left off without creating any additional memory allocations. The calling code looks like the following:

6
1
​
2
   foreach (readLinesFrom(‘myFile.txt’) as $line) {
3
   //do something with $line }
4
​
5
​
6
​

Another feature of generators is the ability to inject or send a value to the generator, which could be useful for stopping the generation process. Consider a simplified version of the xrange() function above:

18
1
​
2
   function xrange($start, $limit, $step = 1) { 
3
   if ($start < $limit) {
4
for ($i = $start; $i <= $limit; $i += $step) {
5
$res = (yield $i);
6
if($res == ‘stop’) {
7
return;//exit the function }
8
} }
9
}
10
$gen = xrange(1, 10);
11
foreach($gen as $v)
12
{
13
if($v == 5) {
14
// stop generating more numbers
15
$gen->send(‘stop’); }
16
echo “{$v}\n”; }
17
​
18
​

The result of the current yield expression can be captured and evaluated. By calling the send function in the client code, a value can be injected into the generator and halt the process.

More information on generators can be found at http://php.net/ manual/en/language.generators.overview.php.

Exception Handling and the Finally Keyword

Exception handling had been added to PHP in version 5. Code can be surrounded in a try-catch block to facilitate the catching of potential errors. Classic uses of exception blocks are file I/O and network I/O functions. Each try is accompanied by at least one catch block and multiple catch blocks can be used to handle different types of exceptions.

PHP 5.5 adds support for the finally keyword. Similar to Java, the finally block is appended to try-catch blocks and it is guaranteed to run regardless of whether an exception occurs within the try block or before normal execution resumes. Here is the general syntax:

12
1
​
2
   $handle= fopen(‘myFile.txt’, ‘w+’); try {
3
// Open a directory and run some code
4
fopen($handle, ‘Some Text’); }
5
catch (Exception $e) {
6
echo ‘Caught exception: ‘, $e->getMessage(), “\n”; }
7
finally { fclose($handle);
8
echo “Close directory”; 
9
}
10
​
11
​
12
​

The finally block is used typically to free up resources that were taken up before or during the execution of the try statement. Adding support for finally is another step at enhancing PHP’s error handling mechanism to compete with other programming languages, and also to improve the quality of error handling code. Unlike Java, however, PHP does not establish a distinction between checked and unchecked exceptions – essentially all exceptions are runtime exceptions.

Security

PHP 5.5 has a new API that facilitates the generation of password hashes using the same underlying library as crypt(), which is a one-way password hashing function available in PHP since version 4. Password hashing is very useful when needing to store and validate passwords in a database for authentication purposes.

The new password_hash() function acts as a wrapper to crypt() making it very convenient to create and manage passwords in a strong and secure manner. Streamlining this API will make it easier for developers to start adopting it over the much older and weaker md5() and sha1() functions, which are still heavily used today.

Since it is built-in to the PHP core, this extension has no dependencies on external libraries, and does not require special php.ini directives to use.

The API consists of the following functions:

FUNCTION NAME DESCRIPTION
password_get_info Returns information about the given hash as an array: salt, cost and algorithm used
password_hash Creates a password hash
password_needs_rehash Checks if the given hash matches the options provided
password_verify Verifies password matches a given hash

Here is some sample code:

19
1
​
2
   // generate new hash
3
$password = ‘MyP@ssword!’;
4
$new_hash = password_hash($password, PASSWORD_DEFAULT); print “Generated New Password Hash: “ + $new_hash + “\n”;
5
// get info about this hash
6
$info = password_get_info($new_hash); v a r_ d u m p ($ i n f o);
7
​
8
// verify hash
9
$isVerified = password_verify($password, $new_hash); if($isVerified) {
10
}
11
print “Password is valid!\n”;
12
// check for rehash
13
$needs_rehash = password_needs_rehash($new_hash, PASSWORD_DEFAULT);
14
if(!$needs_rehash) {
15
print “Password does not need rehash as it is valid”;
16
}
17
​
18
​
19
​

The new hashing API supports a few options when generating password hashes: salt, the algorithm, and a cost.

OPTION NAME DESCRIPTION
salt This is an optional string to base the hashing algorithm on. The new hashing API does not require or recommend the use of a custom salt.
algo The default algorithm built in to PHP 5.5 is the Bcrypt algorithm (also called Blowfish), but you are free to use others supported by the crypt() function such as Blowfish or Standard DES.
cost Associated with an encryption algorithm is a cost value that represents the number of iterations used when generating a hash. In the password hash API, a default baseline value of 10 (2^10 = 1024 iterations) is used, but you can increment this on better hardware. Cost values range from 04 – 31.

More information on password hashing, visit http://php.net/ manual/en/book.password.php.

Section 3

PHP 5.5 Platform Enhancements

The PHP 5.5 release also contains minor enhancements to the language constructs.

Enhancement to foreach( )

Support for list( )

The foreach() statement now supports the unpacking of nested arrays (an array of arrays) to perform quick variable assignments via the list() function. list() had been present in PHP since version 4, but could not be used in this capacity until now.

Let’s see an example:

10
1
​
2
   $vector = [ [0, 1, 2], 
3
                   [3, 4, 5],  
4
                  [2, 1, 2],
5
];
6
foreach ($vector as list($x, $y, $z)) {
7
printf(“Vector components [%d, %d, %d] \n”, $x, $y, $z);
8
}
9
​
10
​

At each iteration of the loop, $x, $y, and $z will be set to each corresponding array index. If there aren’t enough values to fill the array, a PHP notice will be thrown. On the other hand, you could use fewer values to initialize variables:

10
1
​
2
   $array = [ [1, 2],
3
               [3, 4], ];
4
​
5
foreach ($array as list($x)) {
6
// Note that there is no $y here.
7
echo “$x\n”; }
8
​
9
​
10
​

Support for non-scalar keys

PHP 5.5 lifts the restriction on foreach() valid keys to allow arbitrary types, in particular arrays and objects. This change applies only to iterator keys (iterator::key()) present in the loop statement; non-scalar keys still cannot occur in native PHP arrays.

This change is very useful when using the SPL SplObjectStorage iterator, which provides a mapping of objects to data. This dual purpose can be useful when having the need to uniquely identify data with a complex user defined structure.

Suppose you want to uniquely identify cities by its coordinates. Using simple scalar keys will not be enough; for instance, we can use a custom Coordinate class, as such:

12
1
​
2
   $coords = new SplObjectStorage();
3
$ny = new Coordinate(40.7127, 74.0059); 
4
$mia = new Coordinate(25.7877, 80.2241);
5
​
6
$coords [$ny] = “New York”; $coords [$mia] = “Miami”;
7
foreach($coords as $c -> $city) {
8
echo “City: $city | Lat: $c->lat | Long: $c->long”; 
9
}
10
​
11
​
12
​

Before 5.5, the code above would not have been allowed, as the declared key $c is a non-scalar.

Note: as of this writing, the PHP manual for the Iterator::key() function has not been updated to account for the non-scalar return type.

Find more information at http://php.net/manual/en/iterator.key. php.

Arbitrary Expressions and Empty ()

Sometimes you want to perform operations before AngularJS starts. These operations can be configurations, achieving relevant data or anything else you might think about. AngularJS enables you to manually bootstrap the application. You will need to remove the ng-app directive from the HTML and use the angular.bootstrap function instead. Make sure that you declare your modules before using them in the angular.bootstrap function. The following code shows a snippet of using manual bootstrap:

5
1
​
2
   !isset($var) || $var == false
3
​
4
​
5
​

Let’s take a look at some examples:

15
1
​
2
   function is_false() {
3
return false; 
4
}
5
if (empty(is_false())) {
6
echo “Print this line”; 
7
}
8
if (empty(true)) {
9
echo “This will NOT be printed. “; }
10
if (empty(0) && empty(“”) && empty(array())) {
11
echo “This will be printed. “; 
12
}
13
​
14
​
15
​

Overall, empty() is a safe way to check for null or empty conditions. For more information on the use of empty, visit http://php.net/ manual/en/function.empty.php.

Array and String Literal Deferencing

Similar to Perl and Python, PHP 5.5 has added language support for direct dereferencing via the index operator. This provides a quick way to obtain the character or index value of an array or string literal, staring at zero. Examples:

8
1
​
2
   echo ‘Direct Array dereferencing: ‘; 
3
      echo[1,2,3,4,5,6,7,8,9][2]; //willprint3
4
echo ‘String character dereferencing: ‘;
5
echo ‘DZONE’[0]; // will print D
6
​
7
​
8
​

If you’re dereferencing an index value outside of the length of an array or a string, an Undefined offset or Uninitialized string offset error will be thrown, respectively.

Class Name resolution Via :: Class

PHP 5.5 has made the addition of the basic keyword class which, preceded by the scope resolution operator ::, is treated as a static or constant property of a class. This keyword will be used to obtain a string containing the fully qualified name of a class. This is especially useful with namespaced classes. For more information on namespaces, visit http://php.net/manual/en/language.namespaces. php.

For example:

10
1
​
2
   namespace MyAppNs\Sub {
3
class ClassName {
4
}
5
echo ClassName::class;
6
// this will print MyAppNs\Sub\ClassName 
7
}
8
​
9
​
10
​

For more information on class name resolution, visit

http://php.net/manual/en/language.oop5.basic.php - language. oop5.basic.class.class.

Class Name resolution Via :: Class

PHP is an interpreted language; every time a script runs it gets compiled to bytecode form, which is then executed. Since scripts don’t change on every request, it makes sense to include a level of opcode caching (code compilation caching) that will improve the performance of script execution.

The Zend Optimiser + OPcache has been added to PHP as the new OPCache extension, replacing APC bytecode caching. Opcode caching is a platform optimization feature applied to the execution lifecycle of a PHP script. This extension drastically improves the performance of PHP by storing precompiled script bytecode into shared memory and removing the need to reload and parse entire scripts on each request. There have been cases where a performance factor of 3x has been seen by just enabling an OPcode cache.

This extension is bundled into PHP 5.5 but is also available as a PECL package, which can be used with previous versions of PHP. PECL is a repository for the distribution and sharing of PHP extensions.

http://pecl.php.net/package/ZendOpcache

To check whether you are using the Zend OPcode cache, execute the following function from a PHP terminal:

5
1
​
2
   !isset($var) || $var == false
3
​
4
​
5
​

You should see the following included as part of the output:

7
1
​
2
   'version’ => array(2) {
3
‘version’ => string(9) “7.0.4-dev”
4
‘opcache_product_name’ => string(12) “Zend OPcache”
5
​
6
​
7
​

Recommended php.ini settings for effective OPcache functionality:

KEY VALUE
opcache.memory_consumption 128
opcache.interned_strings_buffer 8
opcache.revalidate_freq 60
opcache.fast_shutdown 1
opcache.enable_cli 1
opcache.save_comments enable or disable depending on application
opcache.max_accelerated_files 4000

For more information about the meaning of these directives please visit the OPcache configuration page: http://php.net/manual/en/opcache.configuration.php

New Functions Added

Many functions were added in PHP 5.5 — too many to be listed here. Specifically, the internationalization or localization module was completely revamped. To get the complete list of all functions added, please visit http://php.net/manual/en/migration55.new- functions.php.

In addition, here are some other functions added that are useful to keep at hand:

KEY USAGE
array_column($array, $column_key) When dealing with nested array elements, you can use this function to obtain the values of a specific column
boolval($var) Obtain the boolean value of any type of object
json_last_error_ msg() Obtain the error string of the last json_encode() or json_decode() function call
ysqli::begin_ transaction($flags) Marks the beginning of a transaction
mysqli::release_ savepoint($name) Rolls back a transaction to the named
savepoint
mysqli::savepoint() Sets a named transaction savepoint
Section 4

PHP 5.5 Incompatibilities

PHP 5.5 introduces a few backward incompatible changes as well as some deprecated APIs worth noting. All of these issues should be checked thoroughly when planning to do a migration to 5.5

Deprecations

  1. Ext/mysql will generate an E_DEPRECATED warning when attempting to connect to a database. Use MySQLi or PDO_MySQL extensions instead. The biggest change here is that mysql_ connect() has been deprecated.
  2. The /e escaping modifier in preg_replace() has been deprecated. This modifier was used to ensure that no syntax errors occur when using backreferences in strings with either single or double quotes. Also, you could pass arbitrary PHP code into the replacement parameter. Instead, use preg_replace_callback(), a faster, cleaner, and easier-to-use function. For instance:
    7
    1
    ​
    2
            $line = ‘Hello World’;
    3
    echo preg_replace_callback(‘ /(\\w+)/ ‘,
    4
    function ($matches) {
    5
    return strtolower($matches[0]); },
    6
    $line
    7
    ); // will print hello world
  3. Encryption functions from the mcryt extension have been deprecated:
    5
    1
    ​
    2
              o mcrypt_cbc() 
    3
              o mcrypt_cfb() 
    4
              o mcrypt_ecb() 
    5
              o mcrypt_ofb()

Backward Incompatible Changes

  1. Windows XP and 2003 support were dropped, which means the upgrade path and security fixes for these versions will stop. The Windows build for PHP will now require Windows Vista or newer.
  2. Up until now, PHP language constructs are case-sensitive. Meaning, you could write if-else and for loop statements in any case (including mixed case).
  3. Allcase-insensitivefunctionmatchingforfunction,class,and constant names is now locale-independent and following ASCII rules. This improves support for languages with unusual collating rules, such as Turkish. This may cause issues with code bases that use case- insensitive matches for non-ASCII characters in UTF-8. This was done because some locales (like Turkish) have every unexpected rule for lowercasing and uppercasing. For example, lowercasing the letter “I” gives different results in English and Turkish. Therefore, system functions were moved to ASCII lowercasing.
  4. As a result of the previous point,self, parent,and static keywords are now case-insensitive. Prior to 5.5, these keywords were treated in a case-sensitive manner. This has been resolved; hence, self::CONSTANT and SELF::CONSTANT will now be treated identically.

Backward Incompatible Changes

In PHP 5.6, it is now possible to use scalar expressions involving numeric and string literals in static contexts, such as constant and property declarations as well as default function arguments. Before 5.6, you could only do this with static variables. Let’s take a look:

15
1
​
2
   const ONE = 1;
3
const TWO = ONE + ONE;
4
class MyClass {
5
const THREE = TWO + 1;
6
const ONE_THIRD = ONE / self::THREE;
7
const SENTENCE = ‘The value of THREE is ‘.self::THREE;
8
public function f($a = ONE + self::THREE) {
9
return $a; }
10
}
11
echo (new MyClass)->f(); // prints 4
12
echo MyClass::SENTENCE; // prints The value of THREE is 3
13
​
14
​
15
​

In previous releases, this would have generated parser or syntax errors. PHP 5.6 augments the parsing order allowing PHP expressions as constant values, which can contain variables as well as other constants. Similar to static variable references, you can access a class’sconstantvaluesviathe ::scoperesolutionoperator.

Variadic Functions

This is an enhancement to the variable-length argument list (or varargs) parameters. As of PHP 5.5, you need to use the combination of the functions func_num_args(), func_get_arg(), and func_ get_args() in order work with variable-length arguments.

Dynamic languages such as Python and Ruby use the star operator “*” to tell the interpreter to pack as many parameters provided in a function invocation into an array. Starting with PHP 5.6, arguments may include the ellipsis token to establish a function as variadic, analogous to Java’s ellipsis parameters. The arguments passed in will be treated as an array.

9
1
​
2
   function sum(...$numbers) { $s = 0;
3
foreach($numbers as $n) {
4
$s += $n; }
5
return $s; }
6
echo sum(1, 2, 3, 4); // prints 10
7
​
8
​
9
​

As with any other parameter, you can pass varargs by reference by prefixing the ellipsis operator with an ampersand (&).

Argument Unpacking

In somewhat similar fashion to the use of list()introduced in PHP 5.5, you can use the ellipsis token to unpack a Traversable structure such as an array into the argument list.

8
1
​
2
   function sum($a, $b, $c) {
3
return $a + $b + $c; }
4
echo sum(...[1, 2,2]); // prints 6 $arr = [1, 2, 3];
5
echo add(...$arr); // prints 6
6
​
7
​
8
​

Furthermore, you can mix normal (positional) arguments with varargs, with the condition that the latter be placed at the end of the arguments list. In this case, trailing arguments that don’t match the positional argument will be added to the vararg.

10
1
​
2
   function logMsg($message, ...$args) {
3
echo “${message} : on line ${args[0]} Class:
4
${args[1]}”;
5
}
6
logMsg(“Error”, 32, “MyClass”);
7
// prints Error: on line 32 Class MyClass
8
​
9
​
10
​

Exponentiation

PHP 5.6 has added the operator **, a right-associative operator used for exponentiation, along with a **= for shorthand assignment.

8
1
​
2
   printf(“num= %d “, 2**3**2); // prints num= 512
3
$a = 2;
4
$a **= 3;
5
printf(“a= %d”, $a); // prints a=8
6
​
7
​
8
​

Namespacing and Aliasing

Introduced in PHP 5.3, namespaces provided a way to encapsulate or group a set of items, in very much the same way to how directories group files. Two files with the same name can live in different directories without conflict. The same goes for PHP. This is analogous to Java’s package structure of directories.

Before namespaces existed, PHP developers would include the directory structure as part of their class names, yielding incredibly long class names. In other words, you would see class names like:

PHPUnit_Framework_TestCase

This was the best practice at the moment. This would refer to the class TestCase that lives inside the PHPUnit/Framework directory. Namespaces are designed to solve 2 problems:

  1. 1.Avoid name collisions among application code, PHP core code, and third party libraries
  2. 2. Improve readability by aliasing (shortening) long class names

The use keyword provides developers the ability to refer to an external, fully-qualified name with an alias. This is similar to Python’s use of the import keyword. All versions of PHP that support namespaces and up to PHP 5.5 support aliasing, or importing a class name, interface name, or namespace. PHP 5.6 has extended this behavior to allow aliasing of functions as well as constant names.

Here is an example of the different uses of namespaces and the use keyword. The following statements build on each other:

19
1
​
2
   namespace foo;
3
// Alias (shorten) full qualified class use com\dzone\Classname as Another;
4
// Similar to using com\dzone\NSname as NSname use com\dzone\NSname;
5
// Importing a global class
6
use ArrayObject; // ArrayObject is a global PHP class
7
// Importing a function (PHP 5.6+) use function com\dzone\functionName;
8
// Aliasing a function (PHP 5.6+)
9
use function com\dzomne\functionName as func;
10
// Importing a constant (PHP 5.6+) use const com\dzone\CONSTANT;
11
// Instantiates object of class foo\Another $anotherObj = new namespace\Another;
12
// Similar to instantiating object of class com\dzone\ Classname
13
$anotherObj = new Another;
14
// Calls function com\dzone\NSname\subns\func dzone\subns\func();
15
// Instantiates object of class core class ArrayObject $a = new ArrayObject(array(1));
16
// Prints the value of com\dzone\CONSTANT echo CONSTANT;
17
​
18
​
19
​

Here is an example of the different uses of namespaces and the use keyword. The following statements build on each other:

11
1
​
2
   namespace com\dzone { const FOO = 42;
3
function myFunc() { echo __FUNCTION__; } }
4
namespace {
5
use const com\dzone\FOO;
6
use function com\dzone\ myFunc;
7
echo FOO; // prints 42
8
myFunc (); // prints com\dzone\myFunc }
9
​
10
​
11
​

Debugging

Until now, the most common way to debug PHP scripts was by using the Xdebug extension. Xdebug would instrument a running PHP script by setting up a special connection to the server. Using specific protocols, it could expose the internals of a running script to developers.

PHP 5.6 now includes a built-in interactive debugger called phpdbg implemented as a first-class SAPI (Server API) module. As a result, the debugger can exert complete control over the environment without any additional connections and overhead. This lightweight, powerful debugger will run without impacting the functionality or performance of your code. For more information about the debugger and to install it, visit the homepage:

http://phpdbg.com/

phpdbg has several features including:

  1. Step-through Debugging
  2. Flexible Breakpoints
  3. Easy Access to PHP with built-in eval()
  4. Easy Access to Currently Executing Code
  5. Userland API
  6. SAPI Agnostic - Easily Integrated
  7. PHP Configuration File Support
  8. JIT Super Globals
  9. Optional readline Support - Comfortable Terminal Operation
  10. Remote Debugging Support - Bundled Java GUI

String Comparison

PHP 5.6 added a function called hash_equals()to compare strings in constant time. This is not meant to be used for all string comparison, but rather when there is a specific need to protect or hide the amount of time taken to compare 2 strings. This is very useful to safeguard against timing attacks.

Timing attacks attempt to discover username and/or password lengths by doing a relative comparison of response time differences, as a result of processing a login form with an invalid username against a known valid one.

PHP 5.5 with its simplified password hashing APIs (as discussed before) already makes use of this function.

5
1
​
2
   bool hash_equals ( string $known_string , string $user_string )
3
​
4
​
5
​

Object Info

The magic method __debugInfo has been added in order to control the printed output of an object as a result of calling var_dump(). This is very similar to a class overriding the toString() method in Java.

11
1
​
2
   class MySquareClass { private $val;
3
public function __construct($val) {
4
$this->val = $val; }
5
public function __debugInfo() { return [
6
‘valSquared’ => $this->val ** 2, ];
7
} }
8
var_dump(new C(3));
9
​
10
​
11
​

This will print:

8
1
​
2
   var_dump(new C(3)); 
3
   This will print: object(MyClass)#1 (1) {
4
[“propSquared”]=>
5
int(9) }
6
​
7
​
8
​

Encoding

In PHP 5.6 and onwards, “UTF-8” will be used as the default character encoding for forhtmlentities(), html_entity_ decode() and htmlspecialchars() if the encoding parameter is omitted. The value of the default_charset php.ini will be used to set the default encoding for iconv functions as well as multi-byte mbstring functions.

Section 5

PHP 5.6 Incompatibilities

PHP 5.6 introduces a few backward incompatible changes as well as some deprecated APIs that are worth mentioning. With each new release of PHP, the core team has committed to reducing incompatibility changes going forward.

Deprecations

  1. Methods from an incompatible context are deprecated and will generate an E_DEPRECATED warning. This occurs when invoking a non-static function in a static context. For instance:
    5
    1
    ​
    2
       class A {
    3
    function f() { echo get_class($this); } }
    4
    class B {
    5
    function f() { A::f(); } // incompatible context }
    Support for these calls will later be removed altogether.The mbstring configuration options in regards to character encoding have been deprecated in favor of default_charset.

Backward Incompatible Changes

  1. Array keys won’t be overridden when defining an array as a property of a class via an array literal. Before 5.6, arrays declared as a class property with mixed keys could have array elements silently overridden when an explicit key had the same value as a sequential implicit key. For example:
    8
    1
    ​
    2
       class Myclass {
    3
       const ONE = 1;
    4
    public $array = [ 1 => ‘foo’,
    5
    ‘bar,
    6
    ‘joe’, ];
    7
    }
    8
    var_dump((new C)->array);
    In PHP 5.5, this will output:
    5
    1
    ​
    2
       array(3) { [1]=>
    3
    string(3) “foo” [2]=>
    4
    string(3) “bar” [3]=>
    5
    string(4) “quux” }
    The function json_decode will reject non-lowercase variations of the JSON literals for true, false, and null, following the JSON specification. In line with the new password hashing APIs introduced in PHP 5.5, the Mcrypt functions now require valid keys and initialization vectors (IV) to be provided.
Section 6

Conclusion

In sum, PHP 5.5 and 5.6 have introduced many important language enhancements that improve the overall quality and stability of the platform. Among the most popular enhancements, we find the introduction of function generators and the yield keyword; the addition of the finally block to try-catch statements; a streamlined password hashing API; improved OPcaching; constant scalar expressions, variadic functions, a lightweight debugger, and many additional functions and changes to the core platform.

While these releases did not send tremors through the PHP community, some backward incompatible changes were introduced that can make migration to this platform a bit unnerving. Thus, a degree of caution and overall regression-testing measures must be taken when upgrading production systems to 5.5 or 5.6. The PHP team is strongly committed to making future releases much more backward compatible.

Before migration, please take a look at the following pages, for both 5.5 and 5.6, respectively:

http://php.net/manual/en/migration55.php

http://php.net/manual/en/migration56.php

Like This Refcard? Read More From DZone

related article thumbnail

DZone Article

7 Reasons Why PHP is Best For Web Development
related article thumbnail

DZone Article

How to Perform Custom Error Handling With ANTLR
related article thumbnail

DZone Article

Operational Principles, Architecture, Benefits, and Limitations of Artificial Intelligence Large Language Models
related article thumbnail

DZone Article

How to Ensure Cross-Time Zone Data Integrity and Consistency in Global Data Pipelines
related refcard thumbnail

Free DZone Refcard

Getting Started With Low-Code Development
related refcard thumbnail

Free DZone Refcard

JavaScript Test Automation Frameworks
related refcard thumbnail

Free DZone Refcard

Salesforce Application Design
related refcard thumbnail

Free DZone Refcard

E-Commerce Development Essentials

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: