Function
Function
• In PHP 7, type declarations were added. This gives us an option to specify the
expected data type when declaring a function, and by adding the strict
declaration, it will throw a "Fatal Error" if the data type mismatches.
• In the following example we try to send both a number and a string to the
function without using strict:
• <?php
function addNumbers(int $a, int $b) {
return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is NOT enabled "5 days" is changed to int(5),
and it will return 10
?>
• To specify strict we need to set declare(strict_types=1);. This must be on the very first
line of the PHP file.
• In the following example we try to send both a number and a string to the function,
but here we have added the strict declaration:
<?php declare(strict_types=1); // strict requirement
function addNumbers(int $a, int $b) {
return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is enabled and "5 days" is not an integer, an error will be thrown
?>
• The strict declaration forces things to be used in the intended way.
• PHP Default Argument Value
• The following example shows how to use a default parameter. If we call the function
setHeight() without arguments it takes the default value as argument:
• Example
The include() function does not stop the execution of the script The require() function will stop the execution of the script
even if any error occurs. when an error occurs.
The include() function does not give a fatal error. The require() function gives a fatal error
The include() function will only produce a The require() will produce a fatal error (E_COMPILE_ERROR)
warning (E_WARNING) and the script will continue to execute. along with the warning and the script will stop its execution.