How can Type-Hinting be used in PHP to ensure the correct data type is passed to a function or method?
Type-Hinting in PHP can be used to ensure the correct data type is passed to a function or method by specifying the expected data type in the function or method declaration. This helps prevent errors and improve code clarity by explicitly stating the type of data that should be passed as an argument.
function calculateArea(int $length, int $width) {
return $length * $width;
}
// This function expects two integer values
echo calculateArea(5, 10); // Output: 50
// Passing a string value will result in a TypeError
echo calculateArea('5', '10'); // TypeError: Argument 1 passed to calculateArea() must be of the type int