Home > PHP development services > PHP 7 review: Scalar Type Declarations and Return Type Declarations

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.

Contents

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

Never miss a post! Share it!

Author
Written by
Partner / Department Head
I've been leading projects in Healthcare, Financial and other domains for 14 years.
3.0
1 review

Rate this article

Testimonials

tichen

I expected and demanded a lot of you at Belitsoft company, but you exceeded my expectations. You acted pro-actively, challenged me at the right moments. Thanks!

Martin Beijer

CEO at Ticken B.V. (Netherlands)

EFI

We have been working for over 10 years and they have become our long-term technology partner. Any software development, programming, or design needs we have had, Belitsoft company has always been able to handle this for us.

Bjarne Mortensen

СEO at ElearningForce International (United States, Denmark)

Crimson

They use their knowledge and skills to program the product, and then completed a series of quality assurance tests. We were working in an agile way with them. Belitsoft performed very well throughout our project. We are definitely looking at Belitsoft as a long-term partner.

Eddie Nicholas

Service Delivery Director at Crimson (United Kingdom)

Berkeley

I highly recommend Belitsoft for website design and development. We were up against a tight deadline to launch the project. The work was delivered on time and within budget! I will continue working with Belitsoft as a valued partner for our web development!

Adrienne Herd

Program Administrator at UC Berkeley (United States)

Hathway

We have worked with Belitsoft team over the past few years on projects involving much customized programming work. They are knowledgeable and are able to complete tasks on schedule, meeting our technical requirements. We would recommend them to anyone who is in need of custom programming work.

Kevin M. Rice

Main Partner at Hathway Tech (United States)

Howcast

Belitsoft company is able to make changes instantly. One of our internal engineers has commented about how clean their code is. Belitsoft seems to know what they're doing, which I appreciate.

Darlene Liebman

Co-Founder at HOWCAST MEDIA (United States)

Fraunhofer

It was a great pleasure working with Belitsoft. Software Development Company. New requirements and adjustments were implemented fast and precisely. We can recommend Belitsoft and are looking forward to start a follow-up project.

Renè Reiners

Deputy Head of Division at Fraunhofer FIT (Germany)

Apollo Matrix

Belitsoft company has been able to provide senior developers with the skills to support back end, native mobile and web applications. We continue today to augment our existing staff with great developers from Belitsoft.

Pete Johnson

CEO at Apollo Matrix (United States)

Key2Know

Belitsoft company delivered dedicated development team for our products and technical specialists for our clients time to time custom development needs. We highly recommend that you use this company if you want the same benefits.

Bo Sejer Frandsen

Managing Director at Key2Know A/S in 2012 (Denmark)

Regen Med

We approached BelITsoft with a concept, and they were able to convert it into a multi-platform software solution. Their team members are skilled, agile and attached to their work, all of which paid dividends as our software grew in complexity.

Nicolas Tierney

COO at Regenerative Medicine LLC (United States)

Moblers

Having worked with Belitsoft as a service provider, I must say that I'm very pleased with the company's policy. Belitsoft guarantees first-class service through efficient management, great expertise, and a systematic approach to business.. I would strongly recommend Belitsoft's services to anyone wanting to get the right IT products in the right place at the right time.

Guy Doron

CEO at Moblers (Israel)

Showcast

If you are looking for a true partnership Belitsoft company might be the best choice for you. They have proven to be most reliable, polite and professional. The team managed to adapt to changing requirements and to provide me with best solutions. I strongly recommend Belisoft.

Ivo Downes

Director at ShowCast Limited (Germany)

Let's Talk Business
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.
Contact form
* Maximum file size is 20MB
to top