0
0
PHPprogramming~10 mins

Function declaration and calling in PHP - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Function declaration and calling
Start
Declare function
Call function
Execute function body
Return result (optional)
Continue main program
End
First, you write a function with a name and code inside. Then you call it to run that code. The program runs the function's code and returns a result if given.
Execution Sample
PHP
<?php
function greet() {
  echo "Hello!\n";
}
greet();
?>
This code defines a function greet that prints Hello! and then calls it to show the message.
Execution Table
StepActionEvaluationOutput
1Declare function greetFunction greet is stored
2Call function greet()Function greet runsHello!
3Function greet endsReturn to main program
4Program endsNo more code
💡 Program stops after calling greet and printing Hello!
Variable Tracker
VariableStartAfter CallFinal
greet (function)DeclaredRunningFinished
Key Moments - 2 Insights
Why doesn't the function run when it is declared?
Declaring a function only tells the program what it is. It runs only when you call it, as shown in step 2 of the execution table.
What happens if we call the function multiple times?
Each call runs the function code again. The execution table shows one call, but calling greet() again would print Hello! again.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is printed when greet() is called?
Agreet
BNothing
CHello!
DError
💡 Hint
Check Step 2 in the execution table where the output is shown.
At which step does the function greet finish running?
AStep 2
BStep 3
CStep 1
DStep 4
💡 Hint
Look at the execution table row describing function end.
If we remove the call greet(), what happens?
ANothing is printed
BHello! is printed twice
CHello! is printed once
DSyntax error
💡 Hint
Refer to the variable_tracker and execution_table showing function runs only when called.
Concept Snapshot
PHP function declaration:
function name() { code }

Calling function:
name();

Function code runs only when called.
Use echo inside to print output.
No output if not called.
Full Transcript
In PHP, you first declare a function by writing function name() and putting code inside curly braces. This tells the program what the function does but does not run it yet. When you want to run the function, you call it by writing its name followed by parentheses, like greet(). The program then runs the code inside the function. In the example, greet prints Hello! when called. The execution table shows the function is declared first, then called, which prints Hello!, then the function ends and the program finishes. Variables track the function state from declared to running to finished. Beginners often wonder why the function does not run when declared; it only runs when called. Also, calling the function multiple times runs the code each time. If you remove the call, nothing prints because the function code never runs.