0
0
PHPprogramming~5 mins

Type declarations for parameters in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a type declaration for a parameter in PHP?
A type declaration for a parameter in PHP specifies the expected data type of the argument passed to a function or method. It helps catch errors early by ensuring the correct type is used.
Click to reveal answer
beginner
How do you declare a parameter to accept only integers in PHP?
You add the type before the parameter name, like this: <code>function example(int $number) { }</code>. This means the function expects an integer argument.
Click to reveal answer
intermediate
What happens if you pass a wrong type to a function with a declared parameter type in PHP?
PHP will throw a TypeError at runtime, stopping the program unless caught. This helps prevent bugs caused by wrong data types.
Click to reveal answer
intermediate
Can you declare a parameter to accept multiple types in PHP?
Yes, since PHP 8.0, you can use union types like <code>function example(int|string $value) { }</code> to accept either an integer or a string.
Click to reveal answer
beginner
What is the difference between type declarations and type hints in PHP?
They mean the same thing: specifying the expected type of a parameter. The term 'type hint' was used before PHP 7, now 'type declaration' is more common.
Click to reveal answer
How do you declare a function parameter to accept only strings in PHP?
Afunction example(string $text) {}
Bfunction example($text: string) {}
Cfunction example(text string) {}
Dfunction example($text) : string {}
What error does PHP throw if a wrong type is passed to a typed parameter?
ATypeError
BSyntaxError
CValueError
DRuntimeException
Which PHP version introduced union types for parameters?
APHP 7.4
BPHP 5.6
CPHP 7.0
DPHP 8.0
What does this function declaration mean? function test(array $data) {}
AThe function accepts any type of argument.
BThe function accepts only arrays as argument.
CThe function returns an array.
DThe function accepts only strings.
Can you omit the type declaration for a parameter in PHP?
AOnly in PHP 8 and above.
BNo, all parameters must have a type declaration.
CYes, parameters can be untyped and accept any value.
DOnly for class methods.
Explain how type declarations for parameters improve PHP code quality.
Think about how telling PHP what type to expect helps avoid mistakes.
You got /4 concepts.
    Describe how to declare a parameter that accepts either an integer or a string in PHP.
    Use the vertical bar | to separate types.
    You got /3 concepts.