PHP: Create a Function

PHP is a powerful programming language and one of its greatest assets is the ability to create and call functions. Functions are stored code snippets that activate when called, giving the opportunity to process information or generate actions on command.

The Code

				
					<?php
// create function and give it a name
function functionName() {
//  here goes the code to be executed;
}
// call the function
functionName(); 
?>
				
			

At this moment, we have created a generic and empty function called functionName.  We have also called the function but as it is empty, nothing happens. Next we give it a proper name and write some code for it to perform when called.

Function Statements

First of all, it is important to have in mind the activity or action that the function will do when called! In our example we will make the function display “Hello World” on our screen. It is a very simple task but fundamental to understand how functions work before adding complexity.

Function name

It is very important to name your PHP functions properly. When the code is simple, you might get away with generic names but it will not be very easy to know what a function does, when you have a complex code.

Recommended is to give the function a unique name that is relevant to the function to be performed. For example in our example we want to display “Hello World” for the user, so I will name the function sayHello.

Call the function

Functions are not activated until they are called, this allows the code to activate only when required. To call a function you just need to write the function’s name followed by brackets ( ).

Complete Code

Create a file called sayhello.php with the following code and open it on your browser.

				
					<!DOCTYPE html>
<html>
<head>
<title>Hello, World! Page</title>
</head>
<body>
<?php
// create function and give it a name
function sayHello() {
//  here goes the code to be executed
  echo "Hello world!";
}
// call the function
sayHello(); 
?>
</body>
</html>
				
			

Related Posts