Yogesh Chauhan's Blog

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:

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.

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 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to change value of a span tag using a reference from another div using jQuery?jQueryHow to create two segues with two UIButtons on a single page (Swift 5.0)?SwiftHow to create an empty array in Swift?SwiftHow to pass arguments in SCSS function?SCSSHow to enable and disable button using JavaScript?JavaScriptThe Sort and Compare Functions in JavaScriptJavaScript