The coercive and strict mode in PHP 7

Two mode in PHP 7: strict and coercive mode.

The type of variable in PHP 7 are:

  • int
  • float
  • bool
  • string
  • interfaces
  • array
  • callable

Example 1:Coercive mode

<?php

// Coercive mode

function sum(int ...$ints)

{

return array_sum($ints);

}

print(sum(2, '3', 4.1));echo "<br>";

print(sum(1, '3', 4.1));echo "<br>";

print(sum(0, '3', 4.1));

?>

The result is:

 

Example 2:  Strict Mode

a new feature of PHP 7 is: The Return type declarations has been introduced.

The type are:

  • int
  • float
  • bool
  • string
  • interfaces
  • array
  • callable
<?php

declare(strict_types = 1);

function returnIntValue(int $value): int

{

return $value;

}

print(returnIntValue(5));

?>

 

Example 3: sum of two values:

<?php

// Strict mode

//sum of 2 values

declare(strict_types = 1);

function returnIntValue(int $x, $y): int {

$value=$x+$y;

return $value;

}

print(returnIntValue(14,10));

?>

The operator “??” in PHP 7:

A new feature in PHP 7 is null coalescing operator (??). It replace isset() function.

The following instruction :

$username = $_GET[‘firstname’] ?? ‘not passed’;

returns its first operand if it exists and is not NULL (The value of text zone); otherwise it returns its second operand.

 Example

<?php

// fetch the value of $_GET['user'] and returns 'not passed'

// if username is not passed

$username = $_GET['firstname'] ?? 'not passed';

print($username);

print("<br/>");

 

// Equivalent code using ternary operator

$username = isset($_GET['firstname']) ? $_GET['firstname'] : 'not passed';

print($username);

print("<br/>");

// Chaining ?? operation

$username = $_GET['firstname'] ?? $_POST['firstname'] ?? 'not passed';

print($username);

?>

<br><br>

<form method="get">

First name: <input type="text" name="firstname">

<input type="submit" value="OK" name="ok">

</form>

The result is :

Before execution

 

After clicking on the Button “ok” :feauture