Type Declarations for Params
Part of the Fundamentals section of Coddy's PHP journey — lesson 65 of 71.
PHP is a loosely typed language, meaning variables can hold any type of data. While this flexibility is convenient, it can lead to unexpected bugs when a function receives the wrong type of argument. Type declarations let you specify exactly what types your parameters should accept.
To add a type declaration, place the type name before the parameter:
<?php
function double(int $number) {
return $number * 2;
}
echo double(5);
?>This outputs 10. The int before $number tells PHP this function expects an integer. If someone passes a string like "hello", PHP will produce an error instead of silently causing problems later.
You can use type declarations with multiple parameters:
<?php
function greetUser(string $name, int $age) {
return "$name is $age years old.";
}
echo greetUser("Alice", 25);
?>Common type declarations include int, float, string, bool, and array. Using them makes your code more predictable and helps catch mistakes early, especially as your programs grow larger.
Challenge
EasyRead three lines of input:
- A person's first name (e.g.,
Alice) - A person's last name (e.g.,
Smith) - A birth year (e.g.,
1995)
Create a function called createProfile that accepts three parameters with type declarations:
$firstNameasstring$lastNameasstring$birthYearasint
The function should calculate the person's age (assume the current year is 2024) and return a string in the following format:
[firstName] [lastName] is [age] years old.Call the function with the input values and print the returned result.
Example 1:
If the inputs are Alice, Smith, and 1995, the output should be:
Alice Smith is 29 years old.Example 2:
If the inputs are Bob, Johnson, and 2000, the output should be:
Bob Johnson is 24 years old.Example 3:
If the inputs are Emma, Davis, and 1988, the output should be:
Emma Davis is 36 years old.Cheat sheet
PHP is a loosely typed language, but type declarations allow you to specify what types your parameters should accept, making code more predictable and catching errors early.
To add a type declaration, place the type name before the parameter:
<?php
function double(int $number) {
return $number * 2;
}
echo double(5); // Outputs: 10
?>You can use type declarations with multiple parameters:
<?php
function greetUser(string $name, int $age) {
return "$name is $age years old.";
}
echo greetUser("Alice", 25);
?>Common type declarations include int, float, string, bool, and array.
Try it yourself
<?php
// Read input
$firstName = trim(fgets(STDIN));
$lastName = trim(fgets(STDIN));
$birthYear = intval(fgets(STDIN));
// TODO: Create the createProfile function with type declarations
// The function should accept $firstName (string), $lastName (string), and $birthYear (int)
// Calculate the age (current year is 2024) and return the formatted string
// Call the function and print the result
echo createProfile($firstName, $lastName, $birthYear);
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison OperatorsEquality & IdentityLogical Operators Part 1Logical Operators Part 2Recap - Simple Logic7Arrays Part 2 - Associative
Intro to Associative ArraysAccessing Values by KeyModifying Values by KeyAdding New Key-Value PairsCheck if Key ExistsRecap - Key-Value Data Store10Functions
Declaring & Calling FunctionsFunction ParametersReturning ValuesDefault Parameter ValuesType Declarations for ParamsReturn Type DeclarationsVariable ScopeRecap - Creating Reusable Code2Variables and Data Types
NumbersStrings and QuotesBooleansNaming ConventionsRecap - Variable InitEmpty VariablesString ConcatenationGetting User InputCast to Different Types5Conditional Logic
If StatementIf - ElseThe Ternary OperatorNull Coalescing OperatorSwitch StatementRecap - Making Decisions3Basic Operators
Arithmetic OperatorsModulo OperatorExponentiation OperatorCombined AssignmentIncrement/DecrementOperator PrecedenceRecap - Simple CalculationsString Operators