The real power of PHP comes from its functions. A function is a block of statements that can be used repeatedly in a program. It will not execute automatically when a page loads; it must be called by the script.
A user-defined function declaration starts with the word function, followed by the name you give to that function.
<?php
function writeMsg() {
echo "Hello, welcome to RedoHub!";
}
?>
To call the function, just write its name followed by parentheses (). You can call the same function multiple times wherever needed.
<?php
function writeMsg() {
echo "Hello, welcome to RedoHub!";
}
writeMsg(); // Call the function
?>
writeMessage()).
calculateTotal() instead of func1()).
return statement. Without it, calling the function gives you NULL — the code inside still runs, but there's no value to use afterward.
& before the parameter name.
writeMsg() twice in reachable code causes a fatal "Cannot redeclare" error.
A second example — giving a parameter a default so the function still works if the caller omits it:
<?php
function greet($name = "Guest") {
return "Hello, $name!";
}
echo greet("Nadia"); // Hello, Nadia!
echo greet(); // Hello, Guest!
?>
Q: Can PHP functions have default parameter values?
A: Yes, as shown above — any parameter with a default must come after all parameters that don't have one.
Q: Can a function modify a variable from outside?
A: Only if you pass it by reference using & in the parameter list (function increase(&$value)), or use the global keyword to reach an outer variable directly.
Q: Can I define two functions with the same name?
A: No, not in the same reachable scope — PHP has no function overloading. See the PHP manual's user-defined functions guide for the full rules.