Functions
• Latest topic to be discussed in this lesson is functions.
• The real power of PHP comes from its functions.
• In PHP there are more than 700 built-in functions.
• In previous lessons, we discussed some of built-in functions that php offers, such as function time, date, isset, unset, session_start(), mb_strstr, mb_strlen… etc.
• Now we are going to discuss, user-defined functions, which you are as a programmer build it yourself.
• Functions have an advantage of keeping the browser from executing your script while page loading. How? When you put your script in a function, then it will be executed only when you call the function.
How to create a function?
• Syntax:
• function functionName()
• {
• Code to be executed.
• }
Example:
<?php
function printName($var)
{
echo “<font style=‘font-size:14px’> $var.”</font><Br>”;
}
?>
Function Returns a value:
<?php
function sum($var1,$var2)
{
return $var1 + $var2;
return $var1 + $var2;
}
?>
How to call a function?
<?php
function welcomeMessage()
{
echo “Welcome to my application”;
}
welcomeMessage();
?>
• If the function returns a value, then the function can be called by storing its return value in a variable, or directly echo-ing it.
Example:
<?php
function sum($v1,$v2)
{
$s = $v1 + $v2;
return $s;
}
$x = sum(1,2); // $x = 3
echo sum(2,3); // will print 5
?>
End of lesson 3, to download this lesson as PDF click here: PHP Tutorial - Lesson 3: Introduction to PHP - Part IV
Best Wishes,
Anas Jaghoub
Comments
Post a Comment