YogeshChauhan . com

What is a Strict Requirement in PHP 7 Function Declarations?

in PHP on November 26, 2019

What is a function? Every programmer knows about that. It's a block of statements which can be used again and again throughout the program without writing the whole code. The only condition is that we need to call the function each time want to run those statements. It won't be running on page loads.

PHP has more than 1000 built-in functions.

Now, we all know about user-defined functions and how we can make hem take arguments and then they process the arguments. 

PHP is a loosely types language means we don't need to tell PHP the type of the variable we are declaring. 

Read more about loosely types language in the following article. 

What is the difference between Loosely Typed Language and Strongly Typed Language?

It's the same thing with PHP functions. We don't need to tell the functions about passing argument type and it recognizes itself. But in PHP 7, they introduced this "strict" requirement type declarations. 

Let's take look at the function without "strict" requirement:


<?php
function sum(int $x, int $y) {
    return $x + $y;
}
echo sum(2, "3 days");
// we have not mentioned "strict" so "3 days" will be changed to int(3), and it will return 5
?>

Now take a look at the following example:


<?php declare(strict_types=1); // strict requirement
function sum(int $x, int $y) {
    return $x + $y;
}
echo sum(2, "3 days");
// we have mentioned "strict" so "3 days" will NOT be changed to int(3), and YOU'LL GET AN ERROR 
?>

To make the data type strict, we just need to add one statement which is declare(strict_types=1);

Declaring strict means that the function needs to stick to the data type in function call.

amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

Custom Post Type Template Files in WordPressWordPress@forward rule in SCSS (Sass)SCSSMIN, MAX, COUNT, AVG and SUM in SQLSQL/MySQLHow to deploy Angular App on Dreamhost or Amazon S3 or firebase?AngularLearn how to give a temporary name to a column or to a table using SQL AliasesSQL/MySQLKeyValuePipe in Angular 9Angular