PHP Functions
PHP Functions
• PHP function is a piece of code that can be reused many times. It can
take input as argument list and return value.
• Syntax
• function functionname(){
• //code to be executed
•}
Advantage of PHP Functions
• Code Reusability: PHP functions are defined only once and can be
invoked many times, like in other programming languages.
• Less Code: It saves a lot of code because you don't need to write the
logic many times. By the use of function, you can write the logic only
once and reuse it.
• Easy to understand: PHP functions separate the programming logic.
So it is easier to understand the flow of the application because every
logic is divided in the form of functions.
• PHP Function Arguments
• We can pass the information in PHP function through arguments
which is separated by comma.
• PHP supports Call by Value (default), Call by Reference, Default
argument values and Variable-length argument list.
• <?php
• function addNumbers(int $a, int $b) {
• return $a + $b;
•}
• echo addNumbers(5, "5");
• ?>
• PHP Call By Reference
• Value passed to the function doesn't modify the actual value by
default (call by value). But we can do so by passing value as a
reference.
<!DOCTYPE html>
<html>
<body>
<?php
function add_five(&$value) {
$value += 5;
}
$num = 2;
add_five($num);
echo $num;
?>
</body>
</html>