function
start with the word function, followed by the name of the function
you want to create followed by parentheses i.e. ()
and finally place your function's code between curly brackets {}
.<!DOCTYPE html>
<html>
<head>
<title>PHP Functions</title>
</head>
<body>
<?php
function ftl() {
echo "Free Time Learning...!";
}
ftl(); //calling function
?>
</body>
</html>
We can pass the information in PHP function through arguments. An argument is just like a variable.
Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.
The following example to pass single argument in PHP function.
<!DOCTYPE html>
<html>
<head>
<title>PHP Function Arguments</title>
</head>
<body>
<?php
function Books($book_name) {
echo "$book_name Tutorial.<br />";
}
Books("HTML5");
Books("CSS3");
Books("JavaScript");
Books("jQuery");
Books("Bootstrap");
Books("PHP");
Books("mySQL");
Books("AngularJS");
?>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>PHP Function Arguments</title>
</head>
<body>
<?php
function Books($book_name, $year) {
echo "$book_name Tutorial. Released in $year <br>";
}
Books("HTML5","2014");
Books("CSS3","2001");
Books("JavaScript","1995");
Books("jQuery","2006");
Books("Bootstrap","2011");
Books("PHP","1994");
Books("MySQl","1995");
Books("AngularJS","2010");
?>
</body>
</html>
We can specify a default argument value in function. While calling PHP function if you don't specify any argument, it will take the default argument. The following example of using default argument value in PHP function.
<!DOCTYPE html>
<html>
<head>
<title>PHP Default Argument Value</title>
</head>
<body>
<?php
function my_website($website = "www.freetimelearn.com") {
echo "Website name is : $website <br />";
}
my_website("www.freetimelearning.com");
my_website(); // will use the default value
my_website("www.freetimelearning.xyz");
my_website("www.freetimelearn.xyz");
?>
</body>
</html>
A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code. The following example of PHP function returning a value :
<!DOCTYPE html>
<html>
<head>
<title>PHP Function - Returning Value</title>
</head>
<body>
<?php
function ret_value($x, $y) {
$sum = $x + $y;
return $sum;
}
$return_value = ret_value(10, 20);
echo "Returning value from the function : $return_value";
?>
</body>
</html>
It is possible to assign function names as strings to variables and then treat these variables exactly as you would the function name itself.
The Following example of Dynamic function calls :
<!DOCTYPE html>
<html>
<head>
<title>PHP Dynamic Function Calls</title>
</head>
<body>
<?php
function ftl() {
echo "www.freetimelearning.com <br />";
}
$FreeTimeLearn = "ftl";
$FreeTimeLearn();
?>
</body>
</html>