php · level 1 · unit 7 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A is a recipe card with a name on top.
A function is a set of instructions wrapped up under one name. You write the recipe once, then cook it as often as you like, without copying a single line.
To a function, type function, a name and empty brackets, then a block in curly brackets. Defining it does not run it. It only writes the card.
To it, write its name with brackets and a ;, like cheer();. Every line in the block then runs, top to bottom. Call it twice and it runs twice.
<?php
function cheer() {
echo "Go team!\n";
echo "You can do it!\n";
}
cheer();
cheer(); Change the recipe once and every call uses the new version.
guess first
The call comes first this time. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
cheer();
function cheer() {
echo "Go team!\n";
}
your turn
Your turn. Write your own chant.
Make up a new name for your function, like chant, and type it in all three name blanks. Put any words you like in the quotes, then run it.
fix it
The dog will not bark. Can you fix it?
- The function is written perfectly. Look at the last line, where you try to use it.
- A name on its own does not call a function. PHP hunts for something else called bark and gets stuck.
- Add brackets after bark on the last line, so it says
bark();, then press run.
nailed it
you wrote your very own command. :D
- A function is a set of instructions with a name.
- Define it with
function, a name, brackets and a block. - Call it with its name, brackets and a
;.
new words in your collection
- function
- define
- call
This lesson isn’t saved. A free account remembers every lesson you finish.