YogeshChauhan.com
What is a Strict Requirement in PHP 7 Function Declarations?
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.

dreamhost

Leave a Reply

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to set opacity or transparency using CSS? #3 Pagination in CSS with multiple examples #4 How to make HTML form interactive and using CSS? #5 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

Mar 3 How to embed YouTube or other video links in WordPress? Mar 3 How to change the Login Logo in WordPress? Mar 3 substring() Method in JavaScript Mar 3 Window setInterval() Method in JavaScript Mar 2 How to zoom an element on hover using CSS? Mar 2 the box-sizing property in CSS

You might also like these

RIGHT JOIN in PostgresPostgresJavaScript String fromCharCode() MethodJavaScriptWhat is a Strict Requirement in PHP 7 Function Declarations?PHPCONCAT and CONCAT_WS Functions in PostgresPostgresHow to get start index and end index (as int) of substring in Swift?SwiftFunction Scope in JavaScript for BeginnersJavaScript