Saturday, September 4, 2010

PHP Functions

The real power of PHP comes from its functions.
  • In PHP -there are more than 700 built-in functions available.
  • A function is a block of code that can be executed whenever we need it.

Creating PHP functions:
  • All functions start with the word "function()".
  • Name the function -It should be possible to understand what the function does by its name. The name can start with a letter or underscore (not a number) .
  • Add a "{"-The function code starts after the opening curly brace.
  • Insert the function code.
  • Add a "}"-The function is finished by a closing curly brace.

Example
A simple function that writes my name when it is called:

functionwriteMyName()
{
echo "Hello World";
}

writeMyName();




The output of the code above will be:
Hello world!


PHP Functions -Adding parameters


Our first function (writeMyName()) is a very simple function. It only writes a static string.
To add more functionality to a function, we can add parameters. A parameter is just like a variable.
You may have noticed the parentheses after the function name, like:writeMyName(). The parameters are specified inside the parentheses.


Example

functionwriteMyName($fname)
{
echo $fname. "Refsnes.
";
}
echo "My name is ";
writeMyName("Kai Jim");echo "My name is ";
writeMyName("Hege");echo "My name is ";
writeMyName("Stale");

The output of the code above will be:
My name is Kai JimRefsnes.
My name isHege Refsnes.
My name is StaleRefsnes



 

PHP Functions -Return values 
Functions can also be used to return values. 


Example:

function add($x,$y)
{
$total = $x + $y;
return $total;
}
echo "1 + 16 = " . add(1,16);


The output of the code above will be:
 
 1 + 16 = 17 



 
 































1 comment:

  1. Thanks A Lord For Publish In Your Blog, This Is A Great Things To Learned Many Information. Keep Posting Many Blogs Like This.
    Web portal development company in chennai, Web portal development services in chennai

    ReplyDelete