PHP as programming language and server side scripting was originally using procedural programming, it’s not an object oriented language. In procedural programming, real power of PHP comes from functions ( in the PHP there are more than 700 built functions ). See detail the built in functions in the PHP, please visit PHP Site Reference.

A function in the PHP is a block of code that can be defined once and reused in multiple part of the program. Functions often take multiple parameters that allow we to pass data in and out of our functions. In some cases, a function doesn’t have to take any parameters at all.

We can create function with declare functions by using the keyword function followed by the name we want for the function. In good of the procedural programming practice, we use functions to modularize our code and provide to use in others block of code. The first example function, we can create simple function with no parameters passing into function. Follow the example bellow.

1
2
3
4
5
6
7
 
	function writeFooter() {
        echo "<div id=\"footer\">";
        echo "copyright ".date('Y').".";
        echo " Widya Tehnika";
        echo "</div>";
}

After us create a function, we can invoke it with simply call by name function and leave the parentheses blank.

1
2
3
 
	/* our code to call function */
	writeFooter();

We can create a function more functionality with some parameters. With this function, we can passing some variable to a function. For example, we will create a function, extends previous code with whatever name we pass to it.

1
2
3
4
5
6
 
	function writeFooter($blog_name) {
        echo "<div id=\"footer\">";
        echo "copyright ".date('Y')...$blog_name;
        echo "</div>";
}

Now, when we invoke this function, we will write the following code :

1
2
	/* passing variable to a function */
writeFooter(‘Widya Tehnika’);

In the next example, we will learn how to create a function with a return value. However, a function can only return one thing, although that thing can be any integer, float and others type of variable that we choose. To let a function return a value, we can use the return statement in the our function. see following example bellow.

1
2
3
4
5
6
7
8
9
 
	/* create a function with a return value */
	function multiplierFunction($a, $b) {
		$total_result = $a*$b;
		Return $total_result;
	}
 
/* usage a function with a return value */
multiplierFunction(5,6);

In this discussion, we have succeeded to create a basic function and extends it with a return value.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • ThisNext
  • MisterWong
  • Wists
  • Slashdot
  • Technorati
  • YahooMyWeb