PHP 7 | Features - GeeksforGeeks

22 Apr, 2019
Lots of features have been added in PHP7. After the release of PHP7, performance has been increased by 25-70% for the website. Now we will discuss the PHP7 features one by one through example.
Scalar Datatype Hinting: Scalar datatypes are boolean, integer, float and string. Earlier we were unable to do type hinting for the scalar datatype. We were doing hinting for array or class objects.
Example:
<?php ini_set('display_errors', '1');  class User{}  function test(User $abc) {    var_dump($abc);}  test(new User);?>
Output:
object(User)#1 (0) {
}
Now let’s see how to do type hinting for a scalar data type which is available in Php7
<?php ini_set('display_errors','1');  class User{}   function add(int $a, int $b) {    return $a + $b;}  echo add(3, '34');?>
Output:
37
We are passing a string in the second argument string ’34’ but output we are getting here is the addition of 34 and 3 i.e. 37 because here the strict mode is disabled. Now if you want to restrict this, you need to give a declaration at the top of the file.Example:
<?php declare(strict_types = 1);ini_set('display_errors','1');  class User{}   function add(int $a, int $b) {    return $a + $b;}  echo add(3, '34');?>
Output:
Fatal error: Uncaught TypeError: Argument 2 passed to add() must be of the type integer,
string given, called in /home/cg/root/5012177/main.php on line 11 and defined 
in /home/cg/root/5012177/main.php:7
Stack trace:
#0 /home/cg/root/5012177/main.php(11): add(3, '34')
#1 {main}
  thrown in /home/cg/root/5012177/main.php on line 7
PHP Fatal error:  Uncaught TypeError: Argument 2 passed to add() must be of the type integer,
string given, called in /home/cg/root/5012177/main.php on line 11 and defined 
in /home/cg/root/5012177/main.php:7
Stack trace:
#0 /home/cg/root/5012177/main.php(11): add(3, '34')
#1 {main}
  thrown in /home/cg/root/5012177/main.php on line 7

Now let’s see the example for Boolean. Below is the code for boolean data type.Example:
<?php declare(strict_types = 1);ini_set('display_errors','1');  class User{}   function isBoolean(bool $a) {    var_dump($a);}  isBoolean(true);?>
Output:
bool(true)
Return Type Declaration: In C or C++, define the data type of value that will be return from the function. Now we will see how to do this in Php7.Example:
<?php   declare(strict_types = 1);ini_set('display_errors','1');  function test(): array {    return[];}  var_dump(test());?>
Output:
array(0) {
}
In the above example after declaring a function, need to give data type using: and then return the same data type array in the function test().
Null Coalesce Operator: Null Coalesce operator is “??”. This operator replace basically ternary operator. Earlier we were using ternary operator like below ...
<?php declare(strict_types = 1);ini_set('display_errors','1');  $name = isset($_GET['name']) ? $_GET['name'] : 'Not Found';var_dump($name);?>
Output:
string(9) "Not Found"
Now using ‘??’ operator we can shorten the code.Example:
<?php declare(strict_types = 1);ini_set('display_errors','1');  $name = $_GET['name'] ?? 'Not Found';var_dump($name);?>
Output:
string(9) "Not Found"
Groped Imports and Namespaces: Earlier when we had to define multiple namespaces and classes and use or import a class from one namespace to another namespace ‘use’ keyword wa used and then we had to give namespace with the class name which needs to import.Example:
<?php   namespace Course {    class BTech {    }       class MTech {    }}   namespace Course\Branch {            // CSE is in both Course     // BTech and MTech     class CSE {     }   }   namespace App {      use Course\BTech;      use Course\MTech;      use Branch\CSE;      var_dump(new BTech());      var_dump(new MTech());}  ?>
Output:
object(Course\BTech)#1 (0) {
}
object(Course\MTech)#1 (0) {
}
In the above example, import two classes, but what if you need to use multiple classes from one namespace to another namespace. It will have to write multiple lines of ‘use’ statement defining each and every class which will make your code lengthy. So in PHP7 to solve this problem grouped imports was introduced. Let’s see how the above example will work with the help of grouped imports along with nested namespace.Example:
<?php    namespace Course {    class BTech {    }          class MTech {    }}   namespace Course\Branch {           // CSE is in both Course BTech and MTech     class CSE {     }   }   namespace App {         use Course\{          BTech,          MTech,          Branch\CSE      };         var_dump(new BTech());      var_dump(new MTech());      var_dump(new CSE());}   ?>
Output:
object(Course\BTech)#1 (0) {
}
object(Course\MTech)#1 (0) {
}
object(Course\Branch\CSE)#1 (0) {
}
So grouped imports will reduce the code and will be more readable and convenient.
Combined Comparison/Spaceship Operator: Combined comparison operator is the combination of three operator. These operators are less than, greater than, and equal. This combination of three operator runs and the output will vary depending on the result. Now let’s take an example of this operator.
Example:
<?php    $arr = ['welcome' ,'to' , 'geeksforgeeks'];   usort($arr, function($a, $b) {    return strlen($a) <=> strlen($b); });   var_dump($arr);   ?>
Output:
array(3) {
  [0]=>
  string(2) "to"
  [1]=>
  string(7) "welcome"
  [2]=>
  string(13) "geeksforgeeks"
}
In the above example, we are comparing the length of the words which defined in an array and sort it in ascending order. The usort() is a PHP pre-built function where pass an array as the first parameter and second parameter is user defined function means your own custom logic function. Read more about usort() function from this link usort(). So instead of using manually with if and else, we can use spaceship or combined operator for the same task.
Anonymous Classes: PHP7 introduced anonymous classes, now the question is when to use them? When you were to use a class only once and you don’t want it to be instantiated again. Firstly let’s see how we normally create a class and object.
Example:
<?php class test {  function hiGeeks() {      echo "geeksforgeeks";  }}  $sayGeeks = new test;$sayGeeks->hiGeeks();?>
Output:
geeksforgeeks
Now let’s see how to create an anonymous class.Example:
<?php $anonymous = new class {  private $readme  = "Welcome to geeksforgeeks";  function printOut() {    echo $this->readme;  }};$anonymous -> printOut();?>
Output:
Welcome to geeksforgeeks
Here we can create an object for this class but we can extend another class.Example:
<?php class test {    function hiGeeks() {        echo "geeksforgeeks ";    }}   $sayGeeks = new test;$sayGeeks->hiGeeks();   $anonymous = new class extends test{    private $readme  = "Welcome to geeksforgeeks";    function printOut() {        echo $this->readme;    }};   $anonymous -> printOut();$anonymous -> hiGeeks();?>
Output:
geeksforgeeks Welcome to geeksforgeeksgeeksforgeeks
Closure:: call() method: PHP7 introduced a new method call() which is a shorthand way to invoke a closure while binding an object scope to it. Most of the time in JavaScript we use closures which is anonymous function, In PHP 5 we also use closure but in PHP7 we use it in a different way.Example:
<?php    class User {    private $username;     private $email;   public function __construct($username, $email) {        $this->username = $username;        $this->email= $email;    }}   $getUserEmail = function() {    return $this->username. ' email address is '.$this->email;};   $user = new User('abc','abc@gmail.com');  // Using PHP5 $email = $getUserEmail->bindTo($user, 'User');echo $email().'  ';   // Using PHP7echo $getUserEmail->call($user);?>
Output:
abc email address is abc@gmail.com  abc email address is abc@gmail.com
so call() method make our code cleaner and easy to use.
Generator: Doing programming in Php has become more powerful because of some of the new features introduced like ‘return’ with generators and yield in it. We will see how it’s hierarchy works in PHP7.Example:
<?php    function values() {    yield 200;    yield 300;    return 500;}   $control = values();   foreach ($control as $value) {    echo '<br>'. $value;}  echo '<br>'. $control->getReturn();   ?>
Output:
200300500
In the above example, to get the value of yield we are using foreach loop and to get the value of return we are using getReturn(). Here we need to take care of order to get the value of yield and return. If we will change the order we will get an error.Example:
<?php    function values() {    yield 200;    yield 300;    return 500;}   $control = values();   echo '<br>'. $control->getReturn();   foreach ($control as $value) {    echo '<br>'. $value;}   ?>
Output:
PHP Fatal error:  Uncaught Exception: Cannot get return value of a generator that
hasn't returned in /home/cg/root/6474693/main.php:14
Stack trace:
#0 /home/cg/root/6474693/main.php(14): Generator->getReturn()
#1 {main}
  thrown in /home/cg/root/6474693/main.php on line 14

So in the above example, we are trying to get the value of return first and yield that will give you an error. Also In PHP7, it allows yielding from another generator function. We can write several generator functions and you can allow them to link to another.
Example:
<?php   function values() {          yield from Gen2();          yield 300;          return 500;}  function Gen2() {          yield 'This is from Gen2';          yield 'This is from Gen200';          yield from Gen3();}  function Gen3() {          yield 'This is from Gen3';          yield 'This is from Gen300';}  $control = values();  foreach ($control as $value) {          echo '<br>'. $value;}  echo '<br>'. $control->getReturn();  ?>
Output:
This is from Gen2This is from Gen200This is from Gen3This is from Gen300300500
Error Handling: Error and exceptions implement Throwable interface. We can use try/catch blocks to handle errors objects and exceptions.
Type Error: This error occur when certain type of error doesn’t match a type declaration.Parse Error: This error occur when there is syntax error in code or included file.Assertion Error: This error occurs when condition set by assert is not met.
Type Error: This error occur when certain type of error doesn’t match a type declaration.
Parse Error: This error occur when there is syntax error in code or included file.
Assertion Error: This error occurs when condition set by assert is not met.
In PHP7 we can deal with error in an elegant way and we can have an exception thrown whenever it will occur. Fatal error before Php7 would not invoke the error handler and stop the script and can’t close the resources properly. Let’s see the Throwable interface.
interface Throwable
{
    public function getMessage(): string;
    public function getCode(): int;
    public function getFile(): string;
    public function getLine(): int;
    public function getTrace(): array;
    public function getTraceAsString(): string;
    public function getPrevious(): Throwable;
    public function __toString(): string;
}

Below is the syntax how to use Throwable in try/catch block.
try {
  // Code
}catch(Throwable $e) {
  // Exceptions or Error handling
}

Fatal Error Handling: Below is the example for handling fatal error in a more elegant way and we will also see how to close the resources properly.Example:<?php    class User {           public function __construct() {        echo 'User Construct...<br>';    }           public function __destruct() {       echo 'User Destruct...<br>';     }       }   function run($object) {    $object->hello();}   try {    $user = new User();    run(null);  // Use Error instead of exception to// generate custom error message    } catch (Error $e) {    echo '<strong>Error on Line: '.$e->getLine().' in '        .$e->getFile().'</strong>'. $e->getMessage().'<br>';} finally {    echo 'Finally Ran...<br>';}   ?>Output:User Construct...Error on Line: 16 in /home/cg/root/6474693/main.php
Call to a member function hello() on nullFinally Ran...User Destruct...
Sa o this is how we can deal with fatal error and we can close our resources properly and also create custom message. If we will use ‘Exception’ instead of ‘Error’ in catch block like ‘catch (Exception $e)’, we won’t get a proper message which we have created from our end, So use Error instead of Exception.Type Error and Parse Error Handling: We can handle the type errors and parse errors much like in a similar way like we did for fatal error. Let’s see first how to handle type error. Below is the example where we are trying to get the some of two integers and we are doing type hinting.Example:<?php    class User {           public function __construct() {        echo 'User Construct...<br>';    }           public function __destruct() {       echo 'User Destruct...<br>';     }       }   function sum(int $num1, int $num2) {    return $num1 + $num2;}   try {    $user = new User();    echo sum('Test', 2);} catch(Exception $e) {    echo $e->getMessage();} catch(Error $e) {    echo '<strong>'.get_class($e). 'on line '.        $e->getLine().':</strong>'.$e->getMessage().'<br>';}   ?>Output: 
User Construct...TypeError on line 15:Argument 1 passed to sum() must be
of the type integer, string given, called in /home/cg/root/4010040/main.php on line 21User Destruct...
In the above example we are passing a string and an integer which is giving type error to us because of type hinting used in our function. From the above example we can handle the error properly and we can close the resources as well even though we have error. We are using different functions like get_class(), getLine(), getMessage() to handle the error in most elegant way.Now Let’s take an example to handle parse error. Below is the code where we will receive error due to the syntax error in our file.Example:<?php    class User {        public function __construct() {        echo 'User Construct...<br>';    }           public function __destruct() {       echo 'User Destruct...<br>';     }       }   function sum(int $num1, int $num2) {    return $num1 + $num2;}   try {    $user = new User();          // Syntax error for var_dump in below line    $result = eval("var_dup(1);");} catch(Exception $e) {    echo $e->getMessage();} catch(Error $e) {    echo '<strong>'.get_class($e). ' on line '.$e->getLine()        .':</strong>'.$e->getMessage().'<br>';}   ?>Output: 
User Construct...Error on line 1:Call to undefined function var_dup()User Destruct...

Fatal Error Handling: Below is the example for handling fatal error in a more elegant way and we will also see how to close the resources properly.Example:<?php    class User {           public function __construct() {        echo 'User Construct...<br>';    }           public function __destruct() {       echo 'User Destruct...<br>';     }       }   function run($object) {    $object->hello();}   try {    $user = new User();    run(null);  // Use Error instead of exception to// generate custom error message    } catch (Error $e) {    echo '<strong>Error on Line: '.$e->getLine().' in '        .$e->getFile().'</strong>'. $e->getMessage().'<br>';} finally {    echo 'Finally Ran...<br>';}   ?>Output:User Construct...Error on Line: 16 in /home/cg/root/6474693/main.php
Call to a member function hello() on nullFinally Ran...User Destruct...
Sa o this is how we can deal with fatal error and we can close our resources properly and also create custom message. If we will use ‘Exception’ instead of ‘Error’ in catch block like ‘catch (Exception $e)’, we won’t get a proper message which we have created from our end, So use Error instead of Exception.
Example:
<?php    class User {           public function __construct() {        echo 'User Construct...<br>';    }           public function __destruct() {       echo 'User Destruct...<br>';     }       }   function run($object) {    $object->hello();}   try {    $user = new User();    run(null);  // Use Error instead of exception to// generate custom error message    } catch (Error $e) {    echo '<strong>Error on Line: '.$e->getLine().' in '        .$e->getFile().'</strong>'. $e->getMessage().'<br>';} finally {    echo 'Finally Ran...<br>';}   ?>
Output:
User Construct...Error on Line: 16 in /home/cg/root/6474693/main.php
Call to a member function hello() on nullFinally Ran...User Destruct...

Sa o this is how we can deal with fatal error and we can close our resources properly and also create custom message. If we will use ‘Exception’ instead of ‘Error’ in catch block like ‘catch (Exception $e)’, we won’t get a proper message which we have created from our end, So use Error instead of Exception.
Type Error and Parse Error Handling: We can handle the type errors and parse errors much like in a similar way like we did for fatal error. Let’s see first how to handle type error. Below is the example where we are trying to get the some of two integers and we are doing type hinting.Example:<?php    class User {           public function __construct() {        echo 'User Construct...<br>';    }           public function __destruct() {       echo 'User Destruct...<br>';     }       }   function sum(int $num1, int $num2) {    return $num1 + $num2;}   try {    $user = new User();    echo sum('Test', 2);} catch(Exception $e) {    echo $e->getMessage();} catch(Error $e) {    echo '<strong>'.get_class($e). 'on line '.        $e->getLine().':</strong>'.$e->getMessage().'<br>';}   ?>Output: 
User Construct...TypeError on line 15:Argument 1 passed to sum() must be
of the type integer, string given, called in /home/cg/root/4010040/main.php on line 21User Destruct...
In the above example we are passing a string and an integer which is giving type error to us because of type hinting used in our function. From the above example we can handle the error properly and we can close the resources as well even though we have error. We are using different functions like get_class(), getLine(), getMessage() to handle the error in most elegant way.Now Let’s take an example to handle parse error. Below is the code where we will receive error due to the syntax error in our file.Example:<?php    class User {        public function __construct() {        echo 'User Construct...<br>';    }           public function __destruct() {       echo 'User Destruct...<br>';     }       }   function sum(int $num1, int $num2) {    return $num1 + $num2;}   try {    $user = new User();          // Syntax error for var_dump in below line    $result = eval("var_dup(1);");} catch(Exception $e) {    echo $e->getMessage();} catch(Error $e) {    echo '<strong>'.get_class($e). ' on line '.$e->getLine()        .':</strong>'.$e->getMessage().'<br>';}   ?>Output: 
User Construct...Error on line 1:Call to undefined function var_dup()User Destruct...

Example:
<?php    class User {           public function __construct() {        echo 'User Construct...<br>';    }           public function __destruct() {       echo 'User Destruct...<br>';     }       }   function sum(int $num1, int $num2) {    return $num1 + $num2;}   try {    $user = new User();    echo sum('Test', 2);} catch(Exception $e) {    echo $e->getMessage();} catch(Error $e) {    echo '<strong>'.get_class($e). 'on line '.        $e->getLine().':</strong>'.$e->getMessage().'<br>';}   ?>
Output:
 
User Construct...TypeError on line 15:Argument 1 passed to sum() must be
of the type integer, string given, called in /home/cg/root/4010040/main.php on line 21User Destruct...

In the above example we are passing a string and an integer which is giving type error to us because of type hinting used in our function. From the above example we can handle the error properly and we can close the resources as well even though we have error. We are using different functions like get_class(), getLine(), getMessage() to handle the error in most elegant way.
Now Let’s take an example to handle parse error. Below is the code where we will receive error due to the syntax error in our file.
Example:
<?php    class User {        public function __construct() {        echo 'User Construct...<br>';    }           public function __destruct() {       echo 'User Destruct...<br>';     }       }   function sum(int $num1, int $num2) {    return $num1 + $num2;}   try {    $user = new User();          // Syntax error for var_dump in below line    $result = eval("var_dup(1);");} catch(Exception $e) {    echo $e->getMessage();} catch(Error $e) {    echo '<strong>'.get_class($e). ' on line '.$e->getLine()        .':</strong>'.$e->getMessage().'<br>';}   ?>
Output:
 
User Construct...Error on line 1:Call to undefined function var_dup()User Destruct...

Integer Division Function: PHP7 introduced intdiv() function which takes two parameters one is dividend and other is divisor. The result will be the division as int.Example:
<?php   $value = intdiv(13,4);   var_dump($value);   echo $value;?>
Output:
int(3)
3
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
Comparing two dates in PHP
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?