Functions and scope
Type your parameters and returns, use defaults and understand what a function can see.
What you will be able to do
- Type parameters and return values.
- Use default values for optional arguments.
- Return early instead of nesting.
- Arrow functions capture outer variables automatically.
In plain English
A function is a named, reusable transformation. In PHP, variables outside the function are not automatically visible inside it. Pass data in as parameters and return data out rather than reaching for globals.
<?php
declare(strict_types=1);
function formatMinutes(int $minutes, string $suffix = 'min'): string
{
return $minutes . ' ' . $suffix;
}
$double = fn (int $n): int => $n * 2;
echo formatMinutes(12);
echo "\n" . $double(7);Your turn
EasyWrite a typed helper
Write a function label(string $title, int $count): string that returns "CSS (16)" for those inputs.
PHP · starter
function label(string $title, int $count): string
{
}Check your understanding before moving on.
Knowledge checkQuestion 1
Can a function read a variable defined outside it without passing it in?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.