Functions in PHP

advertisement
6- Functions in PHP
• Prepeared By Dr Maher Abuhamdeh
Functions
• A function is a piece of code in a larger
program. The function performs a specific
task. The advantages of using functions are:
• Reducing duplication of code
• Decomposing complex problems into simpler
pieces.
• Reuse of code
Types of Functions
• There are two basic types of functions.
• Built-in functions
• User defined ones.
1- The built-in functions
• They are part of the PHP language.
• PHP has more than 1000 built-in functions
Examples are: round() or abs(), str_repeat()
str_repeat()
• Definition and Usage
• The str_repeat() function repeats a string a
specified number of times.
• Syntax
str_repeat(string,repeat)
Example
<?php
echo str_repeat("*", 10);
?>
**********
2- PHP User Defined Functions
• A function is a block of statements that can be
used repeatedly in a program.
• A function will not execute immediately when
a page loads.
• A function will be executed by a call to the
function.
Create a User Defined Function in PHP
• A user defined function declaration starts with
the word "function":
• Syntax
function functionName() {
code to be executed;
}
Notes:
• A function name can start with a letter or
underscore (not a number).
• Function names are NOT case-sensitive
• It is prefer to give the function a name that
reflects what the function does.
Example
function PrintMsg() {
echo "Hello PHP!";
}
Use Function in PHP scrpit
• <?php
function PrintMsg() {
echo "Hello PHP!";
}
PrintMsg(); //To call the function,
?>
PHP Function Arguments
• Information can be passed to functions
through arguments.
• 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.
• Arguments are values that are sent to the
function. The functions process the values and
possibly return them back.
Example
<?php
function maximum($x, $y) {
if ($x > $y) return $x;
else return $y;
}
$a = 23;
$b = 32;
$val = maximum($a, $b);
echo "The max of $a, $b is $val ";
?>
The return keyword
• The return keyword is used to return a value
from the function.
Convert Celsius to Fahrenheit
temperature
<?php
function C2F($c) {
return $c * 9/5 + 32;
}
echo C2F(100);
echo "<br>";
echo C2F(0);
echo "<br>";
echo C2F(30);
echo "<br>";
?>
• 212
32
86
PHP Default Argument Value
• If we call the function without arguments it
takes the default value as argument:
Example
• <?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
?>
The height is : 350
The height is : 50
The height is : 135
The height is : 80
• <?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5,10) . "<br>";
echo "7 + 13 = " . sum(7,13) . "<br>";
echo "2 + 4 = " . sum(2,4);
?>
Output
5 + 10 = 15
7 + 13 = 20
2+4=6
Download