How to Declare and Call a Function in PHP ?
In PHP, functions are blocks of reusable code designed to perform specific tasks. They enhance code organization, promote reusability, and improve readability by encapsulating logic into named units. Declaring and calling functions in PHP involves defining the function using the function
keyword, specifying any parameters it may accept, and then invoking the function when needed within the script.
Steps:
- Function Declaration: Use the
function
keyword followed by the function name and a block of code enclosed within curly braces{}
to define a function. - Function Parameters: Define any parameters the function may accept within the parentheses
()
. - Function Body: Write the code that the function will execute within the curly braces
{}
. - Function Call: Invoke the function by its name followed by parentheses
()
containing any required arguments.
Syntax:
// Function declaration
function functionName($param1, $param2, ...) {
// Function body
// Perform specific tasks here
}
// Function call
functionName($arg1, $arg2, ...);
Example: Illustration of declaration and calling a function in PHP
PHP
<?php // Function declaration function greet( $name ) { echo "Hello, $name!" ; } // Function call greet( "John" ); ?> |
Output
Hello, John!
Difference between Function Declaration and Function Call
Function Declaration | Function Call |
---|---|
Defines the structure and behavior of a function | Invokes the function to execute its defined behavior |
Begins with the function keyword followed by the function name and parameters (optional) |
Consists of the function name followed by parentheses containing any required arguments |
Contains the code to be executed when the function is called | Triggers the execution of the function’s code block with specified input values |
Contact Us