PHP Functions
The function is the power of PHP. Which supports both Built-in-function and User-Defined functions.
The function is like a block of code with its own working functionality, It calls from a single label with or without arguments.
How to make user-defined functions in php?
A User-Defined function defines by syntax.
Syntax of the php functions
function function_name() {
some code here;
}
or
function function_name( arguments ) {
some code here;
}
How to call a function in php?
To call a function to write function name with brackets in the script and point semicolon(;) at the end of a function name.
Understand function declaration and how to call a function from this example:
<?php
// Function without parameters
function Test()
{
$var = "Hello php script";
echo $var;
echo "\n";
}
Test();
// Function with parameters
function Sum($m, $n)
{
$o = $m + $n;
return $o;
}
echo Sum(10, 5);
echo "\n";
?>
Output:
Hello php script
15
What is the default argument value of php function and how to use this?
In PHP function you can give default argument value and also give other argument value on the calling of function.
Understand the default argument value of the function from this example:
<?php
// function with default argument value
function Sum($m = 5, $n = 10)
{
$o = $m + $n;
return $o;
}
echo Sum();
echo "\n\n";
echo Sum(25, 56);
echo "\n\n";
echo Sum(150, 25);
echo "\n\n";
echo Sum(30, 78);
echo "\n\n";
?>
Output:
15
81
175
108
How to call a function through a variable?
PHP also supports the variable method to call a function, a variable name has parentheses appended to it.
PHP will look for a function with the same name as whatever the PHP variable evaluates and will attempt to execute it.
Understand call a function through a variable from this example:
<?php
// Variable function
function Test()
{
$var = "Hello php script";
echo $var . "\n";
}
$data = "test"; // This variable name is same as function name
$data(); // This variable name appended to function call
?>
Output :
Hello php script
PHP Built-in-functions
- PHP comes standard with many functions and constructs.
- They have functions that require specific PHP extensions compiled in, otherwise, fatal "undefined function" errors will appear.