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:


<?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.


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
Did you get an error while displaying Special Characters in JavaScript?JavaScriptHow to render lists inside a component in React?ReactHow to add MySQL alternate port and sockets/pipes in WordPress?WordPressHow to Install PHP composer in Mac OS Catalina?PHPHow to get Current Hour, Minute and Second in JavaScript?JavaScriptAdd animated hamburgers menu using Hamburgers collection on GitHubCSS