PHP Functions

Hi everyone,

Functions are very important in PHP. We write PHP scripts to make our page do something and actually the main purpose of functions is this. Do something, Get me something, Take this and give me this.. all these commands are only valid and useful for functions.

There are two types of functions in PHP :

  • Built-in functions: They already exist in PHP, the only thing to do is manipulating them. We already learned some built-in functions in our PHP Strings lesson.
  • Functions built by us: Sometimes Built-in functions are not enough for us and we may need to write our own functions. We will learn how to compose our own functions in this lesson.

Note: To keep the script from being executed when the page loads, you can put it into a function. Because, normally when page loads all of your script codes are executed. A function will be executed by a call to the function. You may call a function from anywhere within a page.

The syntax of a function is:

function functionName({parameters are optional})
{
// code to be executed;
}

Consider:

  • when you compose a function give it a name that reflects what the function does
  • to obey the variable naming rules(If you still don’t know them please see)

Here goes an example:

Assume that you want to greet a user when he first come to your website; the output will be :

Hello User! Welcome to our website!

<?php
function GreetUser()
{
    echo "Hello User! Welcome to our website!";
}
GreetUser();
?>

We use parameters to add more functionality to our functions. For example if we want to greet our user with his name it would be better, wouldn’t it_? Lets alter our function in this way. The output will be :

Hello Mehmet! Welcome to our website!

<?php
function GreetUser($username)
{
    echo "Hello " . $username . "! Welcome to our website!";
}
GreetUser("Mehmet");
?>

Lets make an example of a function that takes two parameters. It will write the username and age of the user. The out put will be :

Hello John! You are 34 years old.

<?php
function WriteInfo($username, $userage)
{
    echo "Hello " . $username . "! You are " . $userage . " years old.";
}
WriteInfo("John", 34);
?>

Lets return a value from our function. To do this, we user return keyword in PHP. The output of the code below will be the same(Hello John! You are 34 years old.).

<?php
function WriteInfo($username, $userage)
{
    return "Hello " . $username . "! You are " . $userage . " years old.";
}
echo WriteInfo("John", 34);
?>

What did we do here? The function returned a string that includes the username and the age of our user. Now our function holds these values as a string. Then we output this info with echo command. So we got the same output as we got before.

In this lesson you’ve learned about functions in PHP. Stay connected to learn more! 😉

Leave a Reply

Your email address will not be published. Required fields are marked *