PHP 7 review: Scalar Type Declarations and Return Type Declarations

PHP 7 introduced new features: scalar type declarations and return type declarations. In this post we will show how these features makes the maintenance of large pieces of code significantly easier by multiple developers and writing more robust tests. For the owner of the large PHP-based application it means more quality with less money spent in a long-term perspective for their custom software development.
Jan 31, 2017

Data types in PHP

All programs in all programming languages are composed of two concepts: data and operations on that data. Each programming language has certain predefined data types that can be recognized by its interpreter/compiler. A data type (or type) is a set of values and operations predefined for those values. PHP interpreter supports such data types as Boolean, integer, float, and string (which are commonly known as scalar data types), compound data types (array and object), and special data types (resource and NULL). There are different operations with data types available in PHP, including “type declarations” and “type juggling”.<

Type declaration in PHP

Type declaration is a statement in a code that requires the interpreter to check if a passed or returned value matches a certain type. If the given value is not of the expected type, then an error is generated. Type declarations (type hints) were in PHP 5, but in PHP 5 we could declare only non-scalar data types and could not declare return types (values that will be returned from a function or a method).<

PHP 7 type juggling for scalar types

How does PHP interpreter understand which data type it must deal with in each particular case when it is not clearly declared? PHP is a dynamically typed language, so it does the so-called «type juggling» wherever possible. «Type juggling» is a process of automatic determination of data type of a variable by PHP interpreter based on a set of predefined rules. Type juggling comes with potential loss of data in PHP5 without any notices. The problem of potential data loss due to type juggling was fixed in PHP 7 with scalar type declarations .

EXAMPLE 1.1 (PHP5)

  1. < ?php
  2. $a='x'; // string
  3. $b=2; //integer
  4. function FunctionName ($a, $b){
  5. return $a * $b;
  6. }
  7. echo FunctionName ($a, $b);
  8. ?>

RESULT: 0 (data loss due to the type juggling and absence of scalar type declaration in PHP5)


EXAMPLE 1.2 (PHP5)

  1. <?php
  2. $a="1text"; // integer due to the type juggling
  3. $b=2; //integer
  4. function FunctionName ($a, $b){
  5. return $a + $b;
  6. }
  7. echo FunctionName ($a, $b);
  8. ?>

RESULT: 3 (integer) data loss without Noticesp


EXAMPLE 1.3 (PHP7)

  1. <?php
  2. $a='x'; // string
  3. $b=2; //integer
  4. function FunctionName ($a, $b){
  5. return $a * $b;
  6. }
  7. echo FunctionName ($a, $b);
  8. ?>

RESULT: Warning: A non-numeric value encountered on line 5 (data loss with Notices)
RESULT:

PHP 7 new feature “scalar type declarations”

Scalar type declarations have been a top requested feature in PHP for a very long time. There has been a long-standing debate regarding the correct way to implement them.

What is scalar type declaration in PHP 7? 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 or bool).

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

 function FunctionName (int $a, int $b){ return $a + $b; }

In the above example, before calling this function, the PHP 7 interpreter will check if $a or $b variables are integers. If they are not, then the PHP 7 interpreter generates a special PHP 7 TypeError exception.

EXAMPLE 2.1 (PHP7)

  1. <?php
  2. // weak mode
  3. $a='x'; // string
  4. $b=2; //integer
  5. function FunctionName (int $a, int $b){
  6. return $a * $b;
  7. }
  8. echo FunctionName ($a, $b);
  9. ?>

RESULT: PHP Fatal error: Uncaught TypeError: Argument 1 passed to FunctionName() must be of the type integer, string given.

EXAMPLE 2.2 (PHP7)

  1. ?php
  2. // weak mode
  3. $a=1; // integer
  4. $b=2; //integer
  5. function FunctionName (int $a, int $b){
  6. return $a + $b;
  7. }
  8. echo FunctionName ($a, $b);
  9. ?>

RESULT: 3 (integer)


EXAMPLE 2.3 (PHP7)

  1. ?php
  2. // weak mode
  3. $a='1'; // integer due to the type juggling
  4. $b=2; //integer
  5. function FunctionName (int $a, int $b){
  6. return $a + $b;
  7. }
  8. echo FunctionName ($a, $b);
  9. ?>

RESULT: 3 (integer)


EXAMPLE 2.4 (PHP7)

  1. ?php
  2. // weak mode
  3. $a='1text'; // integer due to the type juggling
  4. $b=2; //integer
  5. function FunctionName (int $a, int $b){
  6. return $a + $b;
  7. }
  8. echo FunctionName ($a, $b);
  9. ?>

RESULT: PHP Notice: A non well formed numeric value encountered on line 5
RESULT: 3 (integer)


EXAMPLE 2.5 (PHP7)

  1. <?php
  2. // weak mode
  3. $a= 'text'; //  string
  4. $b=2; // integer
  5. function FunctionName (int $a, int $b) {
  6. return $a+$b;
  7. }
  8. echo FunctionName ($a, $b);
  9. ?>

RESULT: PHP Fatal error: Uncaught TypeError: Argument 1 passed to FunctionName() must be of the type integer, string given

PHP 7’ new feature “strict mode”

By default, all PHP 7 files are in weak type-checking mode (as it was in previous versions of PHP interpreter). A new declare() directive is added, strict_types, which takes either 1 or 0. If 1, strict type-checking mode is used for function calls and return statements in this file. The nice thing about the possibility of using different modes is that you don’t have to worry if one library uses a strict mode and another does not - scalar type declarations only work in the file with the function call.


EXAMPLE 3.1 (PHP7)

  1. ?php declare(strict_types=1); // strict mode
  2. $a='1'; // string
  3. $b=2; //integer
  4. function FunctionName (int $a, int $b){
  5. return $a + $b;
  6. }
  7. echo FunctionName ($a, $b);
  8. ?>
RESULT: PHP Fatal error: Uncaught TypeError: Argument 1 passed to FunctionName() must be of the type integer, string given

PHP 7 new feature “return type declarations”

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 4.1 (PHP7)

  1. ?php
  2. //weak mode
  3. $a='1'; //  string
  4. $b=2; // integer
  5. function FunctionName ($a, $b) : string  {
  6. return $a.$b;
  7. }
  8. echo FunctionName ($a, $b);
  9. ?>

RESULT: 12 (string due to the type juggling)


EXAMPLE 4.2 (PHP7)

  1. <?php declare(strict_types=1);
  2. $a=1; //  integer
  3. $b=2; // integer
  4. function FunctionName ($a, $b) : string  {
  5. return $a+$b;
  6. }
  7. echo FunctionName ($a, $b);
  8. ?>

RESULT: PHP Fatal error: Uncaught TypeError: Return value of FunctionName() must be of the type string, integer returned

Backward compatibility with PHP5 intepreter

Code with scalar type declarations or return type declarations will not work with PHP 5 interpreter.


EXAMPLE 5 (PHP5)

  1. ?php declare(strict_types=1);
  2. $a=1; // integer
  3. $b=2; //integer
  4. function FunctionName (int $a, int $b){
  5. return $a + $b;
  6. }
  7. echo FunctionName ($a, $b);
  8. ?>

RESULT: Warning: Unsupported declare 'strict_types'
Catchable fatal error: Argument 1 passed to FunctionName() must be an instance of int, integer given

Blog writers

Subscribe to Belitsoft's Blog for Entrepreneurs

Join successful software startup founders! Get insights from growing companies like, where to get an idea, how to validate it, how to launch, and how to hire people - everything. Enter your email address below (no spam):

Email *

RECOMMENDED FOR YOU

Lead Generation Design of The Best SaaS Websites

If clothes make the man, the design makes the website. That's where potential customers start evaluating a product. The SaaS website can (and should) be an online lead-generation machine, so each component of it has to be as good as possible. As people generally remember the first and the last thing they see, having impressive header and footer can go a long way towards making your product successful. What do some of the best SaaS companies do with their websites’ headers/footers? Look at this list to get and keep in mind some ideas for custom software development while building or redesigning your SaaS website. ...

PHP 7 vs Node.js

Our team is experienced both in PHP programming and Node.js development. We have a portfolio with both PHP-based applications and Node.js-based applications as well as mixed ones. What do we take into account when considering which tool to use in custom software development? ...

The Top 10 Advantages Of Laravel for Cost-Effective Web Development

Laravel framework is very popular for custom software development. It is the Most Starred PHP Framework on Github: more than 35 000 developers from all over the world (mostly from the USA) greatly appreciate robust features of this platform. Based on data of the BuiltWith, Laravel's popular websites verticals include Business, Entertainment, Media, News, Shopping, Technology, Vehicles. Why is Laravel so popular? ...

100% Remote Million-Dollar SaaS Companies

Companies that hire remote (distributed, virtual, dispersed, or dedicated) workers and do it well seem to have a huge leg up on the competition. Let’s learn how these successful SaaS companies use global talents to increase software quality and reduce the cost of rent and office supplies: Basecamp, Buffer, Chargify, Convertkit, Ghost(pro), Groove, Hubstaff, Invision, Olark, and Zapier. As the company where you can find a remote PHP developer, we believe that you could utilize their experience and expertise to build your own full remote SaaS company. ...

SaaS Founders Who Became Rich Starting With MVP

Belitsoft has a huge experience in MVP software development for startups and prototypes for existing brands. MVP is a minimal version of the product with the minimum set of features that is enough to deploy and test the key hypothesis to solve problems of this product’ potential customers. Experts suggest that, in B2B, it’s not an MVP until you sell it. Viable means you can sell it. ...

Profitable SaaS Startup Ideas

The way to get profitable startup idea is not to try to think of startup ideas (including SaaS development). It's to look for problems, preferably problems you have yourself.  In fact, for many entrepreneurs, successful business ideas start out as solutions designed to address a challenge they face personally. Solving the problem that frustrates you may be one of the best ways of finding an idea for your startup. Look at these software developers who turned their problem into success.  ...

Get A Free Quote

Do you have a software development project to implement? We have people to work on it.
We will be glad to answer all your questions as well as estimate any project of yours.
Use the form below to describe the project and we will get in touch with you within 1 business day.

Call us:
Phone - USA
Phone - BELARUS
Skype
EMAIL US:
Contact form