2/9/2016 - 10:30 PM

New Features in the PHP language per Release

New Features in the PHP language per Release

Code Examples

PHP 5.3

  1. Dynamic access to static methods
    class C {
       public static $foo = 123;

    $a = "C";
    echo $a::$foo;
The above example will output:

  1. Nested Exceptions
    class MyCustomException extends Exception {}

    try {
        throw new MyCustomException("Exceptional", 112);
    } catch (Exception $e) {
        /* Note the use of the third parameter to pass $e
         * into the RuntimeException. */
        throw new RuntimeException("Rethrowing", 911, $e);

PHP 5.5

  1. A simple example that reimplements the range() function as a generator (at least for positive step values)
    function xrange($start, $limit, $step = 1) {  
        for ($i = $start; $i <= $limit; $i += $step) {  
            yield $i;  

    echo 'Single digit odd numbers: ';  

     * Note that an array is never created or returned,  
     * which saves memory.  
    foreach (xrange(1, 9, 2) as $number) {  
        echo "$number ";  

    echo "\n";  

The above example will output:

    Single digit odd numbers: 1 3 5 7 9
  1. Foreach list example:
    $array = [  
        [1, 2],  
        [3, 4],  

    foreach ($array as list($a, $b)) {  
        echo "A: $a; B: $b\n";  

The above example will output:

    A: 1; B: 2
    A: 3; B: 4

Further documentation is available on the [foreach](http://php.net/manual/control-structures.foreach.php#control-structures.foreach.list) manual page.
  1. Empty expression example:
    function always_false() {  
        return false;  

    if (empty(always_false())) {  
        echo "This will be printed.\n";  

    if (empty(true)) {  
        echo "This will not be printed.\n";  

The above example will output:

    This will be printed.
  1. Array and string literal dereferencing example:
    echo 'Array dereferencing: ';  
    echo [1, 2, 3][0];  
    echo "\n";  

    echo 'String dereferencing: ';  
    echo 'PHP'[0];  
    echo "\n";  

The above example will output:

    Array dereferencing: 1
    String dereferencing: P
  1. ClassName::class example:

     namespace Name\Space;  
     class ClassName {}  
     echo ClassName::class;  
     echo "\n";  

    The above example will output:


PHP 5.6

  1. Constant Expressions Example
const ONE = 1;
const TWO = ONE * 2;
class C {
    const THREE = TWO + 1;
    const ONE_THIRD = ONE / self::THREE;
    const SENTENCE = 'The value of THREE is '.self::THREE;
    public function f($a = ONE + self::THREE) {
        return $a;
echo (new C)->f()."\n";

The above example will output:

The value of THREE is 3
  1. Constant Array Example
const ARR = ['a', 'b'];
echo ARR[0];

The above example will output:

  1. Variadic Functions Example
function f($req, $opt = null, ...$params) {
    // $params is an array containing the remaining arguments.
    printf('$req: %d; $opt: %d; number of params: %d'."\n",
           $req, $opt, count($params));
f(1, 2);
f(1, 2, 3);
f(1, 2, 3, 4);
f(1, 2, 3, 4, 5);

The above example will output:

$req: 1; $opt: 0; number of params: 0
$req: 1; $opt: 2; number of params: 0
$req: 1; $opt: 2; number of params: 1
$req: 1; $opt: 2; number of params: 2
$req: 1; $opt: 2; number of params: 3
  1. Argument Unpacking Example
function add($a, $b, $c) {
    return $a + $b + $c;
$operators = [2, 3];
echo add(1, ...$operators);

The above example will output:

  1. Exponentiation Example
printf("2 ** 3 ==      %d\n", 2 ** 3);
printf("2 ** 3 ** 2 == %d\n", 2 ** 3 ** 2);
$a = 2;
$a **= 3;
printf("a ==           %d\n", $a);

The above example will output:

2 ** 3 ==      8
2 ** 3 ** 2 == 512
a ==           8
  1. use function and use const Example
namespace Name\Space {
    const FOO = 42;
    function f() { echo __FUNCTION__."\n"; }
namespace {
    use const Name\Space\FOO;
    use function Name\Space\f;
    echo FOO."\n";

The above example will output:

  1. GMP Overloading Example
$a = gmp_init(42);
$b = gmp_init(17);
// Pre-5.6 code:
var_dump(gmp_add($a, $b));
var_dump(gmp_add($a, 17));
var_dump(gmp_add(42, $b));
// New code:
var_dump($a + $b);
var_dump($a + 17);
var_dump(42 + $b);
  1. hash_equals Example
$expected  = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$correct   = crypt('12345', '$2a$07$usesomesillystringforsalt$');
$incorrect = crypt('1234',  '$2a$07$usesomesillystringforsalt$');
var_dump(hash_equals($expected, $correct));
var_dump(hash_equals($expected, $incorrect));

The above example will output:

  1. __debugInfo() Example
class C {
    private $prop;
    public function __construct($val) {
        $this->prop = $val;
    public function __debugInfo() {
        return [
            'propSquared' => $this->prop ** 2,
var_dump(new C(42));

The above example will output:

object(C)#1 (1) {

New features in PHP 5.6 (2014)

Constant expressions

It is now possible to provide a scalar expression involving numeric and string literals and/or constants in contexts where PHP previously expected a static value, such as constant and property declarations and default function arguments.8

It is also now possible to define a constant array using the const keyword.9

Variadic functions via ...

Variadic functions can now be implemented using the ... operator, instead of relying on func_get_args().10

Argument unpacking via ...

Arrays and Traversable objects can be unpacked into argument lists when calling functions by using the ... operator. This is also known as the splat operator in other languages, including Ruby.11

Exponentiation via **

A right associative ** operator has been added to support exponentiation, along with a **= shorthand assignment operator.12

use function and use const

The use operator has been extended to support importing functions and constants in addition to classes. This is achieved via the use function and use const constructs, respectively.13


PHP now includes an interactive debugger called phpdbg implemented as a SAPI module. For more information, please visit the » phpdbg documentation.

Default character encoding

default_charset is now used as the default character set for the htmlentities() , html_entity_decode() and htmlspecialchars() functions. Note that if the (now deprecated) iconv and mbstring encoding settings are set, they will take precedence over default_charset for iconv and mbstring functions, respectively.

The default value for this setting is UTF-8.

php://input is reusable

1php://input` may now be reopened and read as many times as required. This work has also resulted in a major reduction in the amount of memory required to deal with POST data.

Large file uploads

Files larger than 2 gigabytes in size are now accepted.

GMP supports operator overloading

GMP objects now support operator overloading and casting to scalar types. This allows for more expressive code using GMP.14

hash_equals() for timing attack safe string comparison

The hash_equals() function has been added to compare two strings in constant time. This should be used to mitigate timing attacks; for instance, when testing crypt() password hashes (assuming that you are unable to use password_hash() and password_verify() , which aren't susceptible to timing attacks).15


The __debugInfo() magic method has been added to allow objects to change the properties and values that are shown when the object is output using var_dump() .16

gost-crypto hash algorithm

The gost-crypto hash algorithm has been added. This implements the GOST hash function using the CryptoPro S-box tables as specified by » RFC 4357, section 11.2.

SSL/TLS improvements

A wide range of improvements have been made to the SSL/TLS support in PHP 5.6. These include enabling peer verification by default, supporting certificate fingerprint matching, mitigating against TLS renegotiation attacks, and many new SSL context options to allow more fine grained control over protocol and verification settings when using encrypted streams.

These changes are described in more detail in the OpenSSL changes in PHP 5.6.x section of this migration guide.

pgsql async support

The pgsql extension now supports asynchronous connections and queries, thereby enabling non-blocking behaviour when interacting with PostgreSQL databases. Asynchronous connections may be established via the PGSQL_CONNECT_ASYNC constant, and the new pg_connect_poll() , pg_socket() , pg_consume_input() and pg_flush() functions may be used to handle asynchronous connections and queries.

New features in PHP 5.5 (2013)

Generators added

Support for generators has been added via the yield keyword. Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface. 3

finally keyword added

try-catch blocks now support a finally block for code that should be run regardless of whether an exception has been thrown or not.

New password hashing API

A new password hashing API that makes it easier to securely hash and manage passwords using the same underlying library as crypt() in PHP has been added. See the documentation for password_hash() for more detail.

foreach now supports list()

The foreach control structure now supports unpacking nested arrays into separate variables via the list() construct. 4

empty() supports arbitrary expressions

Passing an arbitrary expression instead of a variable to empty() is now supported. 5

array and string literal dereferencing

Array and string literals can now be dereferenced directly to access individual elements and characters. 6

Class name resolution via ::class

It is possible to use ClassName::class to get a fully qualified name of class ClassName. 7

OPcache extension added

The Zend Optimiser+ opcode cache has been added to PHP as the new OPcache extension. OPcache improves PHP performance by storing precompiled script bytecode in shared memory, thereby removing the need for PHP to load and parse scripts on each request. See the installation instructions for more detail on enabling and using OPcache.

foreach now supports non-scalar keys

foreach now supports keys of any type. While non-scalar keys cannot occur in native PHP arrays, it is possible for Iterator::key() to return a value of any type, and this will now be handled correctly.

Improvements to GD

Various improvements have been made to the GD extension, these include:

New features in PHP 5.4 (2012)

  • Support for traits has been added.
  • Short array syntax has been added, e.g. $a = [1, 2, 3, 4]; or $a = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4];.
  • Function array dereferencing has been added, e.g. foo()[0].
  • Closures now support $this.
  • <?= is now always available, regardless of the short_open_tag php.ini option.
  • Class member access on instantiation has been added, e.g. (new Foo)->bar().
  • Class::{expr}() syntax is now supported.
  • Binary number format has been added, e.g. 0b001001101.
  • Improved parse error messages and improved incompatible arguments warnings.
  • The session extension can now track the upload progress of files.
  • Built-in development web server in CLI mode.
  • callable was implemented as a typehint/type declaration.

New features in PHP 5.3 (2009)

  • Support for namespaces has been added.
  • Support for Late Static Bindings has been added.
  • Support for jump labels (limited goto) has been added.
  • Support for native Closures (Lambda/Anonymous functions) has been added.
  • There are two new magic methods, __callStatic() and __invoke().
  • Nowdoc syntax is now supported, similar to Heredoc syntax, but with single quotes.
  • It is now possible to use Heredocs to initialize static variables and class properties/constants.
  • Heredocs may now be declared using double quotes, complementing the Nowdoc syntax.
  • Constants can now be declared outside a class using the const keyword.
  • The ternary operator now has a shorthand form: ?:.
  • The HTTP stream wrapper now considers all status codes from 200 to 399 to be successful.
  • Dynamic access to static methods is now possible1
  • Exceptions can now be nested2
  • A garbage collector for circular references has been added, and is enabled by default.
  • The mail() function now supports logging of sent email via the mail.log configuration directive. (Note: This only applies to email sent through this function.)

Backward incompatible changes

There are various minor backward incompatible changes between various versions. This file only focusses on obvious functional or structural changes. For an exhaustive list see the page for that specific PHP version.

PHP 5.0

  • array_merge() only accepts arrays
  • The global $argc and $argv variables are always available in the CLI version.
  • An object with no properties is no longer considered "empty".
  • Various functions (get_class(), get_parent_class() and get_class_methods()) and magic constants (__CLASS__, __METHOD__, and __FUNCTION__) are case sensitive when reporting the name of the classes/methods as they are declared.
  • Passing an array to a function by value no longer resets the array's internal pointer for that array within the function.

PHP 5.1

  • Code that could potentially produce memory corruption can no longer do so. However, this means that references work slightly different than they did before. The Engine was fixed to 'know' when the reference operation is being used on a value that should not be referenced.

PHP 5.2

  • SplFileObject::getFilename() returns the filename, not relative/path/to/file
  • magic method __toString() will now be called in a string context, that is, anywhere an object is used as a string.
  • Due to an oversight, PHP 5.0.x and 5.1.x allowed abstract static functions in classes. As of PHP 5.2.x, only interfaces can have them.
  • The 'data' URL scheme was added (RFC2397 data: stream).

PHP 5.3

  • realpath() is now fully platform-independent.
  • The call_user_func() family of functions now propagate $this even if the callee is a parent class.
  • The array functions natsort(), natcasesort(), usort(), uasort(), uksort(), array_flip(), and array_unique() no longer accept objects as arguments.
  • Functions with by-reference parameters called by value has changed now emit a fatal error.
  • The trailing slash / has been removed from the SplFileInfo class and other related directory classes.
  • The __toString() magic method can no longer accept arguments.
  • The magic methods __get(), __set(), __isset(), __unset(), and __call() must always be public and can no longer be static.
  • The __call() magic method is now invoked on access to private and protected methods.
  • The func_get_arg(), func_get_args() and func_num_args() can no longer be called from the outermost scope of a file that has been included by calling include or require from within a function in the calling file.
  • The words goto and namespace are now reserved keywords.

PHP 5.4

  • [Safe mode] is no longer supported.
  • [Magic quotes] has been removed.
  • The [register_globals] and [register_long_arrays] php.ini directives have been removed.
  • [Call-time pass by reference] has been removed.
  • The [break] and [continue] statements no longer accept variable arguments (e.g., break 1 + foo() * $bar;). Static arguments still work, such as break 2;.
  • In the [date and time extension], the timezone can no longer be set using the TZ environment variable. Instead you have to specify a timezone using the [date.timezone] php.ini option or [date_default_timezone_set()] function.
  • Non-numeric string offsets - e.g. $a['foo'] where $a is a string - now return FALSE on [isset()] and TRUE on [empty()], and produce a E_WARNING when used. Offsets of types double, bool and null produce a E_NOTICE. $str='abc';var_dump(isset($str['x'])); // false for PHP 5.4 or later, but true for 5.3 or less
  • Converting an array to a string will now generate an E_NOTICE level error.
  • Turning NULL, FALSE, or an empty string into an object by adding a property will now emit an E_WARNING level error, instead of E_STRICT.
  • Parameter names that shadow super globals now cause a fatal error. This prohibits code like function foo($_GET, $_POST) {}.
  • The Salsa10 and Salsa20 [hash algorithms] have been removed.
  • [array_combine()] now returns array() instead of FALSE when two empty arrays are provided as parameters.
  • When [htmlentities()] is used with an asian character sets an E_STRICT level error is emitted.
  • The third parameter of [ob_start()] has changed from [boolean] erase to [integer] flags. Please follow [this example][example01] to write code that is compatible with PHP 5.3 and 5.4.
  • The words callable, insteadof and trait are now reserved keywords.

PHP 5.5

  • All case insensitive matching for function, class and constant names is now performed in a locale independent manner according to ASCII rules.
  • Changes were made to [pack()] and [unpack()] to make them more compatible with Perl. The "Z" format is code now supported. Use this instead of "a", as the behaviour of "a" has changed. Please follow [this example][example02] to write code that is compatible with PHP 5.4 and 5.5.
  • The keywords self, parent and static are now always case insensitive. Prior to PHP 5.5, cases existed where the [self], [parent], and [static] keywords were treated in a case sensitive fashion.
  • The GUIDs that previously resulted in PHP outputting various logos have been removed. This includes the removal of the functions to return those GUIDs: php_logo_guid()](function.php-logo-guid.php), php_egg_logo_guid(), php_real_logo_guid(), [zend_logo_guid()]

PHP 5.6

[php_logo_guid()]: https://php.net/manual/function.php-logo-guid.php) [zend_logo_guid()]: https://php.net/manual/function.zend-logo-guid.php [array_combine()]: https://php.net/manual/function.array-combine.php [boolean]: https://php.net/manual/language.types.boolean.php [break]: https://php.net/manual/control-structures.break.php [Call-time pass by reference]: https://php.net/manual/language.references.pass.php [continue]: https://php.net/manual/control-structures.continue.php [date and time extension]: https://php.net/manual/book.datetime.php [date_default_timezone_set()]: https://php.net/manual/function.date-default-timezone-set.php [date.timezone]: https://php.net/manual/datetime.configuration.php#ini.date.timezone [empty()]: https://php.net/manual/function.empty.php [example01]: https://php.net/manual/function.ob-start.php#function.ob-start.flags-bc [example02]: https://php.net/manual/migration55.incompatible.php#migration55.incompatible.pack [hash algorithms]: https://php.net/manual/book.hash.php [htmlentities()]: https://php.net/manual/function.htmlentities.php [integer]: https://php.net/manual/language.types.integer.php [isset()]: https://php.net/manual/function.isset.php [Magic quotes]: https://php.net/manual/security.magicquotes.php [ob_start()]: https://php.net/manual/function.ob-start.php [pack()]: https://php.net/manual/function.pack.php [parent]: https://php.net/manual/language.oop5.paamayim-nekudotayim.php [register_globals]: https://php.net/manual/ini.core.php#ini.register-globals [register_long_arrays]: https://php.net/manual/ini.core.php#ini.register-long-arrays [Safe mode]: https://php.net/manual/features.safe-mode.php [self]: https://php.net/manual/language.oop5.paamayim-nekudotayim.php [static]: https://php.net/manual/language.oop5.late-static-bindings.php [unpack()]: https://php.net/manual/function.unpack.php