Introduction to Functions in PHP
What is a Function?
In PHP, a function is a block of statements that can be used repeatedly in a program. Functions help to modularize the code, making it more readable and maintainable. A function is defined using the function
keyword, followed by a name, a pair of parentheses, and a block of code enclosed in curly braces.
Defining a Function
Here's a simple example of a function definition in PHP:
function sayHello() {
echo "Hello, World!";
}
?>
In this example, sayHello
is the name of the function, and it contains a single statement that prints "Hello, World!" to the screen.
Calling a Function
Once a function is defined, you can call it by using its name followed by parentheses. Here's how you can call the sayHello
function defined above:
sayHello();
?>
When this code is executed, it will output:
Function Parameters
Functions can also accept parameters, which allow you to pass data to the function. Parameters are specified within the parentheses in the function definition. Here's an example:
function greet($name) {
echo "Hello, " . $name . "!";
}
?>
In this example, the greet
function accepts a single parameter, $name
. You can call this function and pass a value to it like so:
greet("Alice");
?>
This will output:
Returning Values from Functions
Functions can also return values using the return
statement. Here's an example of a function that adds two numbers and returns the result:
function add($a, $b) {
return $a + $b;
}
?>
You can call this function and store the result in a variable like so:
$result = add(3, 4);
echo $result;
?>
This will output:
Default Parameters
PHP allows you to set default values for function parameters. If a parameter is not provided when the function is called, the default value will be used. Here's an example:
function greet($name = "Guest") {
echo "Hello, " . $name . "!";
}
?>
Calling greet()
without any arguments will use the default value:
greet();
?>
This will output:
Variable Scope
Variables declared within a function are local to that function and cannot be accessed outside of it. Here's an example:
function test() {
$localVar = "I am local";
echo $localVar;
}
test();
echo $localVar;
?>
This code will output:
(and then an error because $localVar is not defined outside the function)