Using Type Declarations in PHP 7
October 10, 2017 Comments 0 14 Views

Using Type Declarations in PHP 7

PHP is considered to be a weak typed language. Using type declarations in PHP 7 simply means specifying which type of variable is being set instead of allowing PHP to set this automatically. In essence, this means that PHP does not require you to declare data types. Type declarations can help you define what should occur so that you get the expected results. This can also make your code easier to read.

If we were to create a function for enrolling students, we could require that the first argument be an object of the student class and the second argument to be an array of classes. If we tried to pass just the name instead of an object we would get a fatal error. If we were to pass a single class instead of an array, we would also get an error. We are required to pass a student object and an array.

If we were to try to check for a scalar variable such as a string, PHP 5 expects it to be an object of the class string, not the variable type string. This means you’ll get a Fatal error: Argument 1 passed to stringTest() must be an instance of string, string given.

Scalar Type Hints :

With PHP 7 we now have added Scalar types. Specifically: int, float, string, and bool.

By adding scalar type hints and enabling strict requirements, it is hoped that more correct and self-documenting PHP programs can be written. It also gives you more control over your code and can make the code easier to read.

By default, scalar type-declarations are non-strict, which means they will attempt to change the original type to match the type specified by the type-declaration. In other words, if you pass a string that starts with a number into a function that requires a float, it will grab the number from the beginning and remove everything else. Passing a float into a function that requires an int will become int(1).

The getTotal function receives 2 floats and adds them together while it returns the sum.

Without strict types turned on, PHP attempts to cast, or change, these arguments to match the type specified in the function.

So when we call getTotal with non-strict types using an int of 2 and a string of “1 week”, PHP converts these to floats. The first argument would be changed to 2.0 and the second argument would be changed to 1.0. However, you will get a Notice: because this is not a well formed numeric value. It will then return a value of 3. Which would be completely wrong if we were trying to add days.

When we call getTotal with the float 2.8 and the string of “3.2”, PHP converts the string into the float 3.2. with no notice because it was a smooth conversion. It then returns a value of 6

When we call getTotal with non-strict types using the float 2.5 and the integer 1. The integer gets converted to the float 1.0 and the function returns 3.5

Strict Example :

Additionally, PHP 7 gives us the opportunity to enable strict mode on a file by file basis. We do this by declare(strict_types=1); at the top of any given file. This MUST be the very first line, even before namespaces. Declaring strict typing will ensure that any function calls made in that file strictly adhere to the types specified.

Strict is determined by the file in which the call to a function is made, not the file in which the function is defined.

If a type-declaration mismatch occurs, a “Fatal Error” is thrown and we know that something is not functioning as desired, instead of allowing PHP to simply guess at what we want to happen, which can cause seemingly random and hard to diagnose issues. We’ll look at catching and handling errors in the next section. But for now, let’s look at an example using strict types turned on.

When the declare strict_type has been turned on, the first two calls that pass a string will produce a Fatal error: Uncaught TypeError: Argument 2 passed to getTotal() must be of the type float, string given.

The exception to strict typing with shown in the third call. If you pass an int as an argument that is looking for a float, PHP will perform what is called “widening”, by adding .0 to the end and the function returns 3.5

Return Type Declarations :

PHP 7 also supports Return Type Declarations which support all the same types as arguments. To specify the return type, we add a colon and then the type right before the opening curly bracket.

function getTotal(float $a, float $b) : float {
If we specify the return type of float, it will work exactly like it has been in the previous 2 examples since the type being returned was already a float. Adding the return type allows you to to be sure your function returns what is expected as well as making it easy to see upfront how the function works.

Non-strict int :

If we specify the return type as int without strict types set, everything will work the same as it did without a return type, the only difference is that it will force the return to be an int. In the third call the return value will truncate to 3 because the floating point will be dropped

Strict int

If we turn strict types on, we’ll get a Fatal error: Uncaught TypeError: Return value of getTotal() must be of the type integer, float returned. In this case we’ll need to specifically cast our return value as an int. This will then return the truncated value.

Why?

The new Type Declarations can make code easier to read and forces things to be used in the way they were intended. Some people prefer to use unit testing to check for intended use instead. Having automated tests for your code is highly recommended, but you can use both unit tests and Type Declarations. Either way, PHP does not require you to declare types but it can definitely make code easier to read. You can see right at the start of a function, what is required and what is returned.

Previous Working With PHP & Databases
Next PHP 7 Using New Operators

About author

Rio
Rio 34 posts

Expert web developer working in PHP, Wordpress, Joomla, Magento, Javascript etc.

You might also like

Error Handling in PHP 7

The next feature we going to cover are the changes to Error Handling. Handling fatal errors in the past has been next to impossible in PHP. A fatal error would

PHP 7 Using New Operators

PHP 7 also brings us some new operators. Let’s just cut the talk and directly check how PHP 7 Using New Operators. Spaceship Operator : The spaceship operator, or Combined Comparison

PHP function to sort array alphabetically or numerically in ascending or descending order.

In this article we will walk through with example on how the PHP array sort functions works to sort the arrays key and values in alphabetically/numerically or ascending/descending order. Sort

Post data to third party site using PHP CURL

PHP supports CURL library which allows you to connect and communicate to many different types of servers with many different types of protocols and supports the http, https, ftp etc.

Store passwords securely in PHP to prevent password hacking

While creating an application using PHP there are maximum chances that you have login for which you have to store user data which also contain passwords for login. We will

Secure directory by allowing access to IP address & Deny all using htaccess

Your website may have folders which you want to keep secure access using URL. For example Admin area you want to keep secure to access using particular IP address and

Creating HTML Form with PHP Server Side Validation.

This article will explain how you can create a HTML Form and do server side validation for the form. So the form which will display will be plain HTML and

Difference between echo and print statements

In PHP there are two basic ways to get your output : echo and print statements. We will show the difference between echo and print statements with a working example.

How to detect website is access from Mobile using PHP.

Todays trend shows that maximum number of website access using mobile is increased. People are using smart phone to access the mobile instead of their desktop OR laptop. Because mobile

0 Comments

No Comments Yet!

You can be first to comment this post!

Leave a Reply

11 + 11 =