php · level 2 · unit 7 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Type declarations say what goes in and what comes out.
Write a type before a parameter and PHP checks every value that arrives: function area(int $width, int $height). That is a . The common types are int, float, string, bool and array.
A goes after the brackets, with a colon: function area(...): int. PHP then checks the answer too. means the function hands nothing back. Send the wrong kind of value and PHP stops with a that names the function and the argument.
Number-like strings are still converted, so area("2", 5) works. area("two", 5) does not.
<?php
function area(int $width, int $height): int {
return $width * $height;
}
function show(string $room, int $size): void {
echo "$room: $size square metres\n";
}
show("Kitchen", area(3, 4));
show("Hall", area("2", 5)); Types also work as notes for people reading your code, telling them what each function expects.
guess first
One number, one word. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
function double(int $number): int {
return $number * 2;
}
echo double("21") . "\n";
echo double("lots") . "\n";
your turn
Your turn. Price a cinema ticket.
Type an age as a whole number, then run it. Try a child under 16 and then an adult.
fix it
The cocoa label will not print. Can you fix it?
- Read the TypeError: argument #2,
$price, must be a float, but it was given a string. - Look at the order of the parameters on line 2, then the order of the arguments on line 5.
- Swap the arguments so line 5 says
label("Cocoa", 2.5), then press run.
nailed it
your functions say exactly what they need. :D
int $agesays what a parameter accepts.: intafter the brackets says what comes back,voidfor nothing.- The wrong kind of value stops PHP with a TypeError.
new words in your collection
- type declaration
- return type
- void
- TypeError
This lesson isn’t saved. A free account remembers every lesson you finish.