0
0
PHPprogramming~10 mins

Why strict typing matters in PHP - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to enable strict typing in PHP.

PHP
<?php
[1]

function add(int $a, int $b): int {
    return $a + $b;
}

echo add(5, 10);
Drag options to blanks, or click blank then click option'
Adeclare(strict_types=1);
Bstrict_types=1;
Cenable_strict();
Duse strict;
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to add the declare statement.
Using incorrect syntax like 'strict_types=1;' without declare.
Trying to enable strict typing with a function call.
2fill in blank
medium

Complete the function call to cause a type error when strict typing is enabled.

PHP
<?php
declare(strict_types=1);

function multiply(int $x, int $y): int {
    return $x * $y;
}

// This will cause a type error
$result = multiply([1], 5);
echo $result;
Drag options to blanks, or click blank then click option'
Anull
B10
C5
D"10"
Attempts:
3 left
💡 Hint
Common Mistakes
Passing an integer which is allowed.
Passing null which causes a different error.
Passing a number without quotes which is correct.
3fill in blank
hard

Fix the error by completing the function parameter type declaration.

PHP
<?php
declare(strict_types=1);

function greet([1] $name): string {
    return "Hello, $name!";
}

echo greet("Alice");
Drag options to blanks, or click blank then click option'
Abool
Bint
Cstring
Darray
Attempts:
3 left
💡 Hint
Common Mistakes
Using int or bool which are wrong types for a name.
Not specifying any type which disables strict typing benefits.
4fill in blank
hard

Fill both blanks to create a function that returns the sum only if both inputs are integers.

PHP
<?php
declare(strict_types=1);

function safeAdd([1] $a, [2] $b): int {
    return $a + $b;
}

echo safeAdd(3, 7);
Drag options to blanks, or click blank then click option'
Aint
Bstring
Cfloat
Dbool
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing types like int and string.
Using float or bool which are not integers.
5fill in blank
hard

Fill all three blanks to create a function that returns the uppercase version of a string if it is not empty.

PHP
<?php
declare(strict_types=1);

function shout([1] $text): string {
    if ($text [2] '') {
        return strtoupper([3]);
    }
    return '';
}

echo shout('hello');
Drag options to blanks, or click blank then click option'
Astring
B!==
C$text
D===
Attempts:
3 left
💡 Hint
Common Mistakes
Using loose equality instead of strict.
Not typing the parameter as string.
Returning the wrong variable.