How to Call a Function in PHP: Simple Guide
In PHP, you call a function by writing its name followed by parentheses, like
functionName(). If the function needs inputs, you put them inside the parentheses separated by commas, for example functionName($arg1, $arg2).Syntax
To call a function in PHP, use the function's name followed by parentheses. If the function requires arguments, include them inside the parentheses separated by commas.
- functionName: The name of the function you want to call.
- (): Parentheses indicate a function call.
- Arguments: Optional values passed to the function inside the parentheses.
php
<?php function greet($name) { echo "Hello, $name!"; } greet("Alice"); // Calling the function ?>
Output
Hello, Alice!
Example
This example shows how to define a function that adds two numbers and then call it with two arguments to get the sum.
php
<?php function add($a, $b) { return $a + $b; } $result = add(5, 3); echo "Sum: $result"; ?>
Output
Sum: 8
Common Pitfalls
Common mistakes when calling functions in PHP include:
- Forgetting the parentheses after the function name, which means the function won't run.
- Passing the wrong number of arguments or missing required arguments.
- Calling a function before it is defined (unless using function declarations, which PHP allows).
php
<?php // Wrong: missing parentheses function sayHi() { echo "Hi!"; } // sayHi; // This does nothing // Right: with parentheses sayHi(); ?>
Output
Hi!
Quick Reference
| Action | Syntax Example | Description |
|---|---|---|
| Call function without arguments | functionName(); | Runs the function named functionName with no inputs. |
| Call function with arguments | functionName($arg1, $arg2); | Runs the function with two inputs. |
| Store return value | $result = functionName($arg); | Saves the function's output to a variable. |
| Call built-in function | strlen("text"); | Calls PHP's built-in function to get string length. |
Key Takeaways
Always use parentheses to call a function in PHP, even if it has no arguments.
Pass the correct number of arguments expected by the function to avoid errors.
You can store the result of a function call in a variable for later use.
Calling a function before defining it works with PHP function declarations.
Missing parentheses or wrong arguments are the most common function call mistakes.