PHP Functions

Today I will show you how to create your own functions in PHP and the most important thing is in simple words and in easy manner instead of writing long boring tutorial.

The real power of PHP comes from its functions. In PHP - there are more than almost 700 built-in functions available.

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:

<html>
<body>
 
<?php
 
function writeMyName()
  {
	echo "John Player";
  }
 
writeMyName();
 
?>
 
</body>
</html>

 
Use a PHP Function

Now we will use the function in a PHP script:

<html>
<body>
 
<?php
function writeMyName()
{
	  echo "John Player";
}
 
	echo "Hello world!<br />";
	echo "My name is ";
	writeMyName();
	echo ".<br />That is right, ";
	writeMyName();
	echo " is my name.";
?>
 
</body>
</html>

The output of the code above will be:

Hello world!
My name is John Player.
That is right, John Player is my name.

 
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 1

The following example will write different first names, but the same last name:

<html>
<body>
 
<?php
 
function writeMyName($fname)
{
	  echo $fname . " Player.<br />";
}
 
	echo "My name is ";
	writeMyName("John");
 
	echo "My name is ";
	writeMyName("Jimmy");
 
	echo "My name is ";
	writeMyName("Nancy");
 
?>
 
</body>
</html>

The output of the code above will be:

My name is John Player.
My name is Jimmy Player.
My name is Nancy Player.


Pages : 1 2