Please support if you like my work by payment through upi: sinhamit@icici or payment by bank
account name: Amit Kumar Sinha,
account number: 2646728782
IFSC code: KKBK0005660
SWIFT: KKBKINBB
Type Declaration in Category: PHPlevel2 by amit
🕙 Posted on 2023-06-20 at 06:01:56 Read in Hindi ...
Return Types & More on Type Hinting
In previous page, you have learned that values can be returned/return
statement. Any data-type may be returned, including arrays and objects. A function can not return multiple values, but similar results can be obtained by returning an array
. You can get individual items from that array in many different ways:
<?php
function
numbers( int
$x, int
$y ) {
$sum = $x + $y;
$subt = $x - $y;
$multi = $x * $y;
$div = $x / $y;
$mod = $x % $y;
return
[ $sum, $subt, $multi, $div, $mod ];
}
// 1) Following array destructuring will collect each member of the array individually.
[
$a, $b, $c, $d, $e ]
= numbers( 4, 3 );
echo $a, ' ', $b, ' ', $c, ' ', $d, ' ', $e; // outputs 7 1 12 1.3333333333333 1
echo '<br />';
// 2) Prior to PHP 7.1.0, the only equivalent alternative is using list() construct
list
( $a, $b, $c, $d, $e ) = numbers( 12, 5 );
echo $a, ' ', $b, ' ', $c, ' ', $d, ' ', $e; // outputs 17 7 60 2.4 2
echo '<br />';
/* 3) returned data-type is array, you can also use implode() function to join array elements with a string, json_encode()
function which returns the JSON representation of a value, etc. */
foreach
( numbers( 64, 6 ) as
$item ) {
echo $item . ' ';
} // outputs 70 58 384 10.666666666667 4 ?>
In the above code, you can see a typical example which is generally used to extract multiple values as result from a custom function. $a, $b, $c, $d, $e are variable names, which will store individual items from the returned array. The first method used in above example is called array destructuring, in which these newly declared variable names are placed within []
square brackets. The second method used is older method in which list()
function is used. There are many ways in which data from an array can be extracted. In later lessons, you will see that data from a DATABASE can be extracted using while
loop.
Type Declaration:
In previous page, you have seen that bool int float string array
(reserved keywords) are used as type-hinting for parameters. Type declarations can be added to function arguments, return values, and, as of PHP 7.4.0, class properties. They ensure that the value is of the specified type at call time, otherwise a TypeError is thrown. Aliases for the above scalar types are not supported. Instead, they are treated as class or interface names. For example, using boolean
as a type declaration will require the value to be an instanceof
the class or interface boolean, rather than of type bool
.
<?php function test(boolean $param) {}
test(true); // outputs ERROR in PHP 8, as follows: ?>
Warning: "boolean" will be interpreted as a class name. Did you mean "bool"? Write "\boolean" to suppress this warning in C:\xampp\
Fatal error: Uncaught TypeError: test(): Argument #1 ($param) must be of type boolean, bool given, called in C:\xampp\
Type declaration of a returned value can also be handled in a custom function. The syntax for return type declaration is written after ()
parentheses and :
(colon symbol). Let's see some simple examples:
<?php
function
addition():int
{
$result = 3.4 + 4.2; var_dump( $result );
echo '<br />';
return
$result;
} // return type is int
var_dump( addition() ); // outputs float(7.6)<br />int(7)?>
In the above example, you can see that $result = 3.4 + 4.2; outputs float(7.6), when var_dump()
is used inside the custom function. However, the return type is int
, and therefore, the last line in above example outputs int(7) and value after . (decimal point) is truncated. However, when the above example is used in strict mode, the TypeError is shown:
Fatal error: Uncaught TypeError: addition(): Return value must be of type int, float returned in C:\xampp\
Following example will not output ERROR even in strict mode. mixed
type declaration is introduced in PHP 8.0.0 and it is either of bool int float string array object resource null data types. It means that any of these data types can be taken (as arguments) in a custom function, and can also be returned as OUTPUT.
<?php
function
max_int_value( mixed
$param ):mixed
{
return $param + 1;
}
var_dump( max_int_value( PHP_INT_MAX ) ); // outputs float(9.2233720?>
Union Type
Union types are available as of PHP 8.0.0. A union type declaration accepts values of multiple different simple types, rather than a single one. In a custom function, you can use |
(pipe symbol, just above the Enter key, use Shift key also) in between two or more simple types.
<?php
function
cube( int|float
$param ):int|float
{
return $param ** 3;
}
var_dump( cube( 4 ) ); // outputs int(64)?>
mixed
type declaration is equivalent to the object|
Nullable Type
As of PHP 7.1.0, type declarations can be marked nullable by prefixing the type name with a ?
(question mark). This signifies that the value can be of the specified type or null
. When you remove ?
(question mark) from the parameter in following example, and null is passed as an argument in custom function cuberoot(), the ERROR will be shown as below.
<?php
function
cuberoot( ?float
$param ):?float
{
return $param ** (1/3);
}
var_dump( cuberoot( 3 ) ); // outputs float(1.44224957?>
Fatal error: Uncaught TypeError: cuberoot(): Argument #1 ($param) must be of type float, null given, called in C:\xampp\
Nullable union types
The null type is supported as part of unions, such that int|
can be used to create a nullable union. The existing ?float
notation is considered a shorthand for the common case of float|
. Caution: null cannot be used as a standalone type.
false pseudo-type
The false
literal type is supported as part of unions, and is included as for historical reasons many internal functions return false
instead of null for failures. A classic example of such a function is strpos(). Caution: false
cannot be used as a standalone type (including nullable standalone type).
As such, false, false|null
and ?false
are not permitted. The true literal type does not exist. If bool
is used in union type, false cannot be used additionally, i.e. bool|false is not allowed. Also, int|INT is not allowed.
Intersection types
An intersection type declaration accepts values which satisfies multiple class-type declarations, rather than a single one. Intersection types are specified using the syntax T1&T2&.... Intersection types are available as of PHP 8.1.0.
Return only types
void
void
is a return type indicating the function does not return any value. Therefore it cannot be part of a union type declaration. It is available as of PHP 7.1.0. Even you want to return NULL
from a custom function, ERROR will be shown as below.
<?php function coo():void { return NULL; } var_dump( coo() ); // Outputs ERROR ?>
Fatal error: A void function must not return a value (did you mean "return;" instead of "return null;"?) in C:\xampp\
<?php function doo():void { return; } var_dump( doo() ); // outputs NO ERROR: NULL ?>
<?php function foo():void { echo "Hello"; } var_dump( foo() ); // Outputs HelloNULL ?>
never
never
is a return type indicating the function does not return. This means that it either calls exit()
function, throws an exception, or is an infinite loop. Therefore it cannot be part of a union type declaration. Available as of PHP 8.1.0. never
is, in type theory parlance, the bottom type. Meaning it is the subtype of every other type and can replace any other return type during inheritance.
static
The value must be an instanceof
the same class as the one the method is called in. static
is available as of PHP 8.0.0.
In this page, you have been introduced with many new reserved keywords, for example static void instanceof never
, which may have overwhelmed you. In advance PHP section, it will be appropriate to explain each of these keywords and functions. For example, exit()
function is frequently used when you want to redirect someone to another web-page, such as payment methods, etc.
Leave a Comment:
Amit Sinha March 2nd, 2023 at 9:30 PM
😃 😄 😁 😆 😅 😂 😉 😊 😇 😍 😘 😚 😋 😜 😝 😶 😏 😒 😌 😔 😪 😷 😵 😎 😲 😳 😨 😰 😥 😢 😭 😱 😖 😣 😞 😓 😩 😫 😤
Ribhu March 3rd, 2023 at 9:30 PM
🐵 🐒 🐶 🐩 🐺 🐱 🐯 🐅 🐆 🐴 🐎 🐮 🐂 🐃 🐄 🐷 🐖 🐗 🐽 🐏 🐑 🐐 🐪 🐫 🐘 🐭 🐁 🐀 🐹 🐰 🐇