Sunday 31 July 2011

PHP - Functions

PHP - Functions

A function is just a name we give to a block of code that can be executed whenever we need it. This might not seem like that big of an idea, but believe me, when you understand and use functions you will be able to save a ton of time and write code that is much more readable!

For example, you might have a company motto that you have to display at least once on every webpage. If you don't, then you get fired! Well, being the savvy PHP programmer you are, you think to yourself, "this sounds like a situation where I might need functions."


Tip: Although functions are often thought of as an advanced topic for beginning programmers to learn, if you take it slow and stick with it, functions can be just minor speedbump in your programming career. So don't give up if you functions confuse you at first!

Creating Your First PHP Function


When you create a function, you first need to give it a name, like myCompanyMotto.
It's with this function name that you will be able to call upon your function, so make it easy to type and understand.

The actual syntax for creating a function is pretty self-explanatory, but you can be the judge of that.
First, you must tell PHP that you want to create a function. You do this by typing the keyword function followed
by your function name and some other stuff (which we'll talk about later).

Here is how you would make a function called myCompanyMotto. Note: We still have
to fill in the code for myCompanyMotto.


PHP Code:

<?php
function myCompanyMotto(){
}
?>

Note: Your function name can start with a letter or underscore "_", but not a number!

With a properly formatted function in place, we can now fill in the code that we want our
function to execute. Do you see the curly braces in the above example "{ }"? These braces define
where our function's code goes. The opening curly brace "{" tells php that the function's code is starting and a closing
curly brace "}" tells PHP that our function is done!

We want our function to print out the company motto each time it's called, so that sounds like it's a job for the echo command!


PHP Code:

<?php
function myCompanyMotto(){
    echo "We deliver quantity, not quality!<br />";
}
?>

That's it! You have written your first PHP function from scratch! Notice that the code that appears within a function is just the same as any other PHP code.

Using Your PHP Function

Now that you have completed coding your PHP function, it's time to put it through a test run. Below
is a simple PHP script. Let's do two things: add the function code to it and use the function twice.

PHP Code:

<?php
echo "Welcome to Tizag.com <br />";
echo "Well, thanks for stopping by! <br />";
echo "and remember... <br />";
?>


PHP Code with Function:

<?php
function myCompanyMotto(){
    echo "We deliver quantity, not quality!<br />";
}
echo "Welcome to Tizag.com <br />";
myCompanyMotto();
echo "Well, thanks for stopping by! <br />";
echo "and remember... <br />";

myCompanyMotto();
?>

Display:

Welcome to Tizag.com

We deliver quantity, not quality!

Well, thanks for stopping by!

and remember...

We deliver quantity, not quality!



Although this was a simple example, it's important to understand that there
is a lot going on and there are a lot of areas to make errors. When you are creating a function, follow
these simple guidelines:

  • Always start your function with the keyword function
  • Remember that your function's code must be between the "{" and the "}"
  • When you are using your function, be sure you spell the function name correctly
  • Don't give up!

PHP Functions - Parameters

Another useful thing about functions is that you can send them information that
the function can then use. Our first function myCompanyMotto isn't all that
useful because all it does, and ever will do, is print out a single, unchanging string.

However, if we were to use parameters, then we would be able to add some extra functionality!
A parameter appears with the parentheses "( )" and looks just like a normal PHP variable.
Let's create a new function that creates a custom greeting based off of a person's name.

Our parameter will be the person's name and our function will concatenate this
name onto a greeting string. Here's what the code would look like.

PHP Code with Function:

<?php
function myGreeting($firstName){
    echo "Hello there ". $firstName . "!<br />";
}
?>


When we use our myGreeting function we have to send it a string containing someone's name, otherwise
it will break. When you add parameters, you also add more responsibility to you, the programmer!
Let's call our new function a few times with some common first names.

PHP Code:

<?php
function myGreeting($firstName){
    echo "Hello there ". $firstName . "!<br />";
}
myGreeting("Jack");
myGreeting("Ahmed");
myGreeting("Julie");
myGreeting("Charles");
?>

Display:


Hello there Jack!

Hello there Ahmed!

Hello there Julie!

Hello there Charles!

It is also possible to have multiple parameters in a function. To separate multiple parameters
PHP uses a comma ",". Let's modify our function to also include last names.

PHP Code:

<?php
function myGreeting($firstName, $lastName){
    echo "Hello there ". $firstName ." ". $lastName ."!<br />";
}
myGreeting("Jack", "Black");
myGreeting("Ahmed", "Zewail");
myGreeting("Julie", "Roberts");
myGreeting("Charles", "Schwab");
?>


Display:

Hello there Jack Black!

Hello there Ahmed Zewail!

Hello there Julie Roberts!

Hello there Charles Schwab!

PHP Functions - Returning Values

Besides being able to pass functions information, you can also have them return a value.
However, a function can only return one thing, although that thing can be any integer, float, array, string, etc. that you choose!

How does it return a value though? Well, when the function is used and finishes executing, it sort of changes from being a function name into being a value. To capture this value you can set a variable equal to the function. Something like:


  • $myVar = somefunction();

Let's demonstrate this returning of a value by using a simple function that returns the sum of two integers.

PHP Code:

<?php
function mySum($numX, $numY){
    $total = $numX + $numY;
    return $total; 
}
$myNumber = 0;

echo "Before the function, myNumber = ". $myNumber ."<br />";
$myNumber = mySum(3, 4); // Store the result of mySum in $myNumber
echo "After the function, myNumber = " . $myNumber ."<br />";
?>

Display:

Before the function, myNumber = 0

After the function, myNumber = 7

When we first print out the value of $myNumber it is still set to the original value of 0.
However, when we set $myNumber equal to the function mySum, $myNumber
is set equal to mySum's result. In this case, the result was 3 + 4 = 7, which was successfully
stored into $myNumber and displayed in the second echo statement!

PHP Functions - Practice Makes Perfect

If you are new to programming, then this lesson might or might not seem like overkill. If you
are having a hard time understanding lessons, the best piece of advice would be to do your best
the first time, then be sure to come back tomorrow and next week and see if it makes
anymore sense. Chances are, after going through this tutorial more than once, with
breaks in between, this topic will be mastered.

No comments:

Post a Comment

VMware Cloud Learning Video's

Here is a nice summary list of all VMworld US 2018 Breakout session with the respective video playback & download URLs. Enjoy! Bra...