New features in PHP 5.6

Here is list of New features in PHP 5.6

1) Variadic functions via …
2) Argument unpacking via …
3) Changes in File uploads
4) Importing namespace functions
5) Exponentiation Operator in PHP (**)

1) Variadic functions via …

Currently variadic functions are implemented by fetching the function arguments using func_get_args() . If we want to pass random number of argument to function then we have to slice that argument after func_get_args()

for example:-


class MySQL implements DB {
   protected $pdo;
   public function query($query) {
   $stmt = $this->pdo->prepare($query);
   $stmt->execute(array_slice(func_get_args(), 1));
   return $stmt;
  }
  // ...
}

$userData = $db->query('SELECT * FROM users WHERE id = ?', $userID)->fetch();

In PHP 5.6


class MySQL implements DB {
   public function query($query, ...$params) {
   $stmt = $this->pdo->prepare($query);
   $stmt->execute($params);
   return $stmt;
  }
  // ...
}

$userData = $db->query('SELECT * FROM users WHERE id = ?', $userID)->fetch();

The …$params syntax indicates that this is a variadic function and that all arguments after $query should be put into the $params array. Using the new syntax both of the issues mentioned above are solved.

2) 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.

Before PHP 5.6


<?php
function addElements($a, $b, $c, $d) {
return $a + $b + $c + $d;
}

addElements(1,2,3,4);

?>

// Output: 10

In PHP 5.6


<?php

$elements = [2,3,4];
echo addElements(1, ...$elements);
?>

3) Changes in File uploads :-

File Upload size increases to 2GB now.

4) Importing Namespaced Functions and Constants

In PHP 5.6 we can import of namespaced functions and constants directly into other classes.

Right now we are doing this using classes, interface and traits


namespace FooTest {
const STATUS = 1;
function helloWorld() {
# ...
}
}

namespace {
use FooTest as Roop;
var_dump(RoophelloWorld());
}

In PHP 5.6 this is achieved via the use function and use const constructs, respectively.


namespace {
use function FooTesthelloWorld;
use const FooTestSTATUS;
}

5) Exponentiation Operator in PHP :-

In PHP 5.6 new right associative ** Operator has been added to support exponentiation . We can use it assignment operator as well (**=).


<?php
    printf("3 ** 3 ==      %d\n", 3 ** 3); 
    
    printf("2 ** 3 ** 2 == %d\n", 2 ** 3 ** 2);
    // As it is right associative (3 ** 2) = (3 * 3 ) = 9
    // In second part (2 ** 9) = (2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2) = 512

    $a = 3;
    $a **= 3;
    
    printf("a ==           %d\n", $a);
?>

Output :-

27
512
27
(Visited 41 times, 1 visits today)