CodeBlanks Logo Icon CodeBlanks

Calling functions

PHP course · Beginner · Lesson 72/116

Learn to call a function by its name with parentheses.

Calling functions

To run a function, write its name followed by parentheses: greet();. This is called a call. When called, the function body runs from top to bottom.

You can call the same function as many times as you like. Writing greet(); greet(); runs the body twice. The call may sit below or above the definition; PHP registers functions while loading the file.

Call and definition order

PHP registers top-level function definitions while loading the file. So a call may be written before the definition. For readability, though, it is common to keep definitions above and calls below.

Once a function is defined, you can call it from anywhere in the same file as many times as you wish; you decide the number of calls. Multiple functions may sit side by side as well.

Exercise Call the same function twice

Define a parameterless function named announceStart. In the body, write echo "Starting!" . "\n";. Then call the function twice.

Show example solution
Define it, then write announceStart(); twice.
Example solution:
<?php
// Define announceStart and call it twice
function announceStart() {
    echo "Starting!" . "\n";
}
announceStart();
announceStart();

Test yourself

  1. Complete the function call

    function startEngine() {
        echo "Vroom";
    }
    
    ____;
    Show answer
    function startEngine() {
        echo "Vroom";
    }
    
    startEngine();
  2. What is the output of the code below?

    function ding() {
        echo "X";
    }
    
    ding();
    ding();
    ding();
    • X X X
    • X
    • XXX
    • X, X, X
    Show answer

    XXX — Correct. Three calls produce three X's side by side; echo adds no space.

  3. Match calling terms

    greet
    Function name
    greet()
    Call expression
    function greet() { ... }
    Definition

All lessons in Beginner