Kode Blog - Inspiring And Empowering Developers.
In the previous tutorial, we looked at what PHP 7 is and what it can do for us. This tutorial will look at scalar type declarations and a simple practical example. Scalar type declaration is sometimes called "type hinting". It basically allows us to specify the data type of a variable. For example, if you want to sum two integer values, you can explicitly tell PHP to treat the parameters as integers instead of letting PHP decide that for you.
We will cover the following topics
For you to successfully complete this tutorial, you should have/know the following.
Specifying the data type has a number of advantages. Let’s look at some of these advantages
$a = 6
, and $b = "x"
. The sum is 6
. If you multiple $a
and $b
, then you will get 0
as the result. This is because the sting "x"
is evaluated to 0
and the computation goes smoothly. In a financial system, this can lead to loss of income. Type hinting throws an error if the conversion fails as in the above example."Uncaught TypeError: Argument 2 passed to sum () must be of the type integer, string given,..."
. PHP 7 allows you to catch Errors in a try block to avoid fatal errors. We will cover error handling in more detail in another tutorial.One of the things that we love about PHP is its flexibility with data types. The scalar type declaration has not taken that away from you. Let’s now look at the Scalar Declaration Types.
Type hinting in PHP 7 is done in three ways namely;
int $a
argument. Passing in a value of "8"
is acceptable. Coercive technical will convert the string value 8
to an int
then perform the desired operation on the data. If you pass in a value such as "x"
, this will throw an error because the value "x"
cannot be coerced into an integer.int $x
. Passing in a value of "8"
for the argument $x
throws an error. This is because the passed in value "8" is of string data. PHP will not try to convert the value for you like we did using coercion.Now that we have laid a good foundation, let’s build a hut on it. In this section, we will create a simple project that demonstrates the implement of scalar type declaration in PHP 7.
Let’s assume we are developing a simple program that multiplies two numbers and returns the result.
I am using XAMPP on windows so I will just create a new directory php7-scalar-types
in C:\htdocs\xampp
Open none.php
and add the following code
<?php
function getSubTotal($quantity, $price){
return $quantity * $price;
}
echo "String parameter values returned : " . getSubTotal("3","2100");
echo "<br>";
echo "String parameter values (quantity as letter) returned : " . getSubTotal("x","2100");
echo "<br>";
echo "Integer parameter values returned : " . getSubTotal(3,2100);
HERE,
getSubTotal($quantity, $price){…}
accepts two parameters $quantity
and $price
to calculate the sub totalecho…. getSubTotal(x,y)
tests different data types as input to the function and displays the result in the web browser.Load the following URL in your web browser
http://localhost/php7-scalar-types/none.php
You will get the following results
HERE,
coercive.php
Add the following code
<?php
function getSubTotal(int $quantity, int $price){
return $quantity * $price;
}
echo "String parameter values returned : " . getSubTotal("3","2100");
echo "<br>";
echo "String parameter values (quantity as letter) returned : " . getSubTotal("x","2100");
echo "<br>";
echo "Integer parameter values returned : " . getSubTotal(3,2100);
HERE,
function getSubTotal(int $quantity, int $price){…}
the function getSubTotal(x,y)
accepts two arguments of int
data types. This means any argument value passed in will be converted to an integer
before performing any operations on the data.int $quantity, int $price
the int
at the beginning declares the value data typeLoan the following URL into your web browser
http://localhost/php7-scalar-types/coercive.php
You will get the following results
Fatal error: Uncaught TypeError: Argument 1 passed to getSubTotal() must be of the type integer, string given
, called in C:\xampp\htdocs\php7-scalar-types\coercive.php on line 9 and defined in C:\xampp\htdocs\php7-scalar-types\coercive.php:3 Stack trace: #0 C:\xampp\htdocs\php7-scalar-types\coercive.php(9): getSubTotal('x', '2100') #1 {main} thrown in C:\xampp\htdocs\php7-scalar-types\coercive.php on line 3HERE,
'x'
could not be coerced into an integer.Add the following code
<?php
declare(strict_types=1);
function getSubTotal(int $quantity, int $price){
return $quantity * $price;
}
echo "Integer parameter values returned : " . getSubTotal(3,2100);
echo "<br>";
echo "String parameter values returned : " . getSubTotal("3","2100");
echo "<br>";
echo "String parameter values (quantity as letter) returned : " . getSubTotal("x","2100");
HERE,
declare(strict_types=1);
sets strict typing to true. The default value is 0. This declaration should be the first line in a file or else PHP will throw an error. Strict types is applied on a file basis. It is not made global.Load the following results
http://localhost/php7-scalar-types/strict.php
You will get the following results
Fatal error: Uncaught TypeError: Argument 1 passed to getSubTotal() must be of the type integer, string given
, called in C:\xampp\htdocs\php7-scalar-types\strict.php on line 11 and defined in C:\xampp\htdocs\php7-scalar-types\strict.php:5 Stack trace: #0 C:\xampp\htdocs\php7-scalar-types\strict.php(11): getSubTotal('3', '2100') #1 {main} thrown in C:\xampp\htdocs\php7-scalar-types\strict.php on line 5HERE,
Scalar Type Declaration helps us to write better code when dealing with variables and PHP still offers us the flexibility of weak typing.
The next tutorial will look at PHP 7 Scalar Type Declarations. In a nutshell, you can now have the option specify the variable data type when declaring variables.
If you found this tutorial useful, support us by using the social media buttons to like and share the tutorial. If you didn’t find it useful, please use the comments section below to let us know how we can do better next time.
Subscribe to our newsletter, like our Facebook fan page or follow us on Twitter to get free updates when we publish new tutorials
Date Published: 2016-05-22