Header Ads Widget

Responsive Advertisement

Ticker

6/recent/ticker-posts

Return Type Declarations in PHP 7

 In PHP 7, a new feature, Return type declarations has been introduced. Return type declaration specifies the type of value that a function should return.

What is return type declarations in PHP7? Return type declaration is specifying the expected data types of the result that a function or a class method should return. Due to return type declaration, PHP, for example, can convert the integer result into a string before returning the result of the function.

EXAMPLE

<?php declare(strict_types=1);
$a=1; // integer
$b=2; // integer
function FunctionName ($a, $b) : int {
return $a+$b;
}
echo FunctionName ($a, $b);
?>

It produces the following browser output − 3

Following types for return types can be declared. (int, float, bool, string, interfaces or array)

What is scalar type declaration in PHP 7?
In PHP 7, a new feature, Scalar type declarations, has been introduced.


Scalar type declaration has two options −

  • coercive – coercive is default mode and need not to be specified.
  • strict – strict mode has to explicitly hinted.

Following types for function parameters can be enforced using the above modes −

Scalar type declaration means the statement to a function to accept arguments (parameters) or return values only of the given scalar data type (int, float, string, interfaces, array, or bool).

Example – Coercive Mode

<?php
   // Coercive mode
   function FunctionName(int ...$ints) {
      return array_sum(="pln">$ints);
   }
   print(FunctionName(1, '2', 3.1));
?>

It produces the following browser output − 6

Example – Strict Mode

<?php
   // Strict mode
   declare(strict_types=1);
   function FunctionName(int ...$ints) {
      return array_sum($ints);
   }
   print(FunctionName(1, '2', 3.1));
?>

It produces the following browser output −
Fatal error: Uncaught TypeError: Argument 2 passed to sum() must be of the type integer, string given, …

To specify a scalar type declaration, the name of the scalar data type should be added before the parameter name

If you have any query or suggestions, feel free to ask me via the comment section below.

must watch some other topics :

cake PHP training institute
cake PHP training course
cake php training online

Post a Comment

0 Comments