2.7. User-Defined

Perhaps the most powerful feature of PHP is the ability to define and execute functions from within your code. A function is a named block of code that you declare within your scripts that you can call at a later time. Functions can accept any number of arguments and can return a value using the return statement.

The basic format of a function requires that you first identify the function using the function reserved word in front of a string that serves as the function's name. This string can contain any alphanumeric characters and underscores, but it must not start with a number. You enclose any arguments you want in parentheses after the function name. Note that you still must include the parentheses even if the function doesn't require that you pass any arguments.

NOTE

Reserved words are special terms that cannot be used for function names. These include the word function, control structure names, and several other terms which will be noted as they come up. You can find a full list of reserved words at http://us2.php.net/manual/en/reserved.php.

Begin by declaring your first function in test.php:

<?php

    function sayHello()
    {
        echo "Hello world!";
    }

    // Execute the function
    sayHello();

?>

The function produces the following output when you call it:

Hello world!

To add arguments, you place variables inside the function declaration's parentheses, separated by commas. You can use these arguments within the function to determine the function's return value:

<?php

    function meet($name)
    {
        echo "Hello, my name is $name. Nice to meet you! <br />";
    }

    meet("Jason");

?>

For example, calling meet("Jason") produces the following output:

Hello, my name is Jason. Nice to meet you!

2.7.1.

2.7.1.1. Returning Values from Functions

Most of the time, you won't want to immediately the result of a function call immediately. To store the result in a variable, you use the return statement discussed earlier. Add the following code to test.php:

<?php

/*
 * Based on the time passed to the function in military (24 hour)
 * time, returns a greeting
 */
function greet($time)
{
    if($time<12)
    {
        return "Good morning!";
    }
    elseif($time<18)
    {
        return "Good afternoon!";
    }

else
    {
        return "Good evening!";
    }
}

$greeting = greet(14);

echo "$greeting How are you?";

?>

PHP stores the result of greet()in the $greeting variable, which you can use later to display a time-sensitive greeting to the user. When you set 14 (2 PM) as your parameter and run this script in your browser, you get the following output:

Good afternoon! How are you?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.138.202