In Php, Scalar Type Declarations two different types options :
1. Coercive mode : coercive mode is a default mode and need not to be specified.
EXAMPLE :: COERCIVE MODE
<?php
function sum(int ...$ints)
{
return array_sum($ints);
}
print "<pre>";
print_r(sum(2,3,4));
print"</pre>";
?>
------------ ****** ------------
OUTPUT:
9
2. Strict mode : Strict mode need to be explicitly type hinted.
There are number of functions parameters can be forced to using modes.
1 int
2 float
3 Boolean
4 string
5 interface
6 array
7 callable
Example 1:
<?php
declare(strict_types = 1);
function add(int ...$ints)
{
return array_sum($ints);
}
print "<pre>";
print_r(add('string',3,4,5,7,8,10)); // throw an error
print "</pre>";
?>
In above example if we pass a string in add function then it will throw an error because of strict mode.
It will throws an error like this :
( ! ) Fatal error: Uncaught TypeError: Argument 1 passed to add() must be of the type integer, string given, called in D:\PHP1\wamp\www\wordpress\Basics\ScalarTypeDeclaration\std.php on line 39 and defined in D:\PHP1\wamp\www\wordpress\Basics\ScalarTypeDeclaration\std.php on line 35.
Example 2: ( strict mode in class )
<?php
declare(strict_types =1);
class A
{
public $a;
public $b;
public $c;
public function add(int $a,int $b,int $c) : int
{
return $c = $a+$b+$c;
}
}
$obj = new A();
echo $obj->add(1,20,30);
?>
------------ ****** ------------
OUTPUT:
51
In above example if we pass a string in add function then it will throws an error.
<?php
declare(strict_types =1);
class A{
public $a;
public $b;
public $c;
public function add(int $a,int $b,int $c) : int{
return $c = $a+$b+$c;
}
}
$obj = new A();
echo $obj->add(1,20,"scalar type declaration example" );
?>
Fatal error: Uncaught TypeError: Argument 3 passed to A::add() must be of the type integer, string given, called in D:\PHP1\wamp\www\wordpress\Basics\ScalarTypeDeclaration\std.php on line 53 and defined in D:\PHP1\wamp\www\wordpress\Basics\ScalarTypeDeclaration\std.php on line 47
Example 3:
<?php
declare(strict_types=1);
class A{
public $str ="Scalar Type Declaration";
public function show_method() : string{
return $this->str;
}
}
$obj = new A();
echo $obj->show_method();
?>
------------ ****** ------------
OUTPUT:
Scalar Type Declaration.