Basics
Creating a Document
Head and Body Elements
Formatting Text
Creating Lists
Embedding Images
URLs Explained
Linking to Documents
Creating Tables
Forms Form Basics
Input and Textarea
Select Lists
Frames Framesets
The Frame Element
Nested Framesets
Targetting Frames
Inline Frames
Tips and Tricks Meta Tags
Transition Effects
HTML Generators Create a Document
Create a List
Create a Table
HTML
Basics
Implementing CSS
CSS Syntax
Pseudo Classes/Elements
CSS Classes
CSS Properties Font Properties
Color and Background
Text Properties
Border Properties
Margins and Padding
Size and Position
Tips and Tricks Menu Buttons
Special Effects
CSS
Basics
Running a Script
Variables
Expressions and Operators
Objects.Properties.Methods
The Date Object
Strings
Regular Expressions
Defining RegExp Patterns
Branches and Conditions
Loops
Arrays Array Basics
Array Methods
Sorting Arrays

User-Defined Functions
Cookies
Windows
Frames
Tips and Tricks Image Replacement
Using Includes
Form Validation
Debugging
JavaScript
Basics
Creating a Script
Running a Script
Variables
Expressions and Operators
Strings Strings Basics
Strings and Substrings
Replacing Substrings
Regular Expressions
Branches and Conditions
Loops
Arrays Array Basics
Array Functions
Sorting Arrays
User-Defined Functions
Include and Require
Uploading Files
File Functions
Session Variables
Tips and Tricks Page Templates
Form Reply Scripts
Form Validation
JavaScript to PHP
PHP
Basics
Create and Drop
Show and Describe
Insert, Update and Delete
Querying
Join Queries
Functions
Table Locking
PHP/MySQL Functions Accessing a Database
Querying with PHP
Create and Drop with PHP
Insert and Update with PHP
Frequently Used Functions MySQL
Basics
Layout and Navigation
Page Content Style
Web Page Copy
Graphics and Animation
HTML Forms
Accessibility
Legal Requirements
MySQL

Home > PHP > User-Defined Functionsprinter version

PHP User-Defined Functions

Library functions have already been demonstrated in this tutorial but it's also possible to create your own PHP functions.

Functions provide a way to group PHP statements into blocks that are reusable - making for more compact code and easier maintenance.

Functions are first defined then called within the script in the same way as library functions. Functions can be defined anywhere within a script but it's normal to define them at the start.

A function may have no arguments (sometimes called parameters) or it may have many. A Function may also return arguments.

Defining a Function



Example of a function() Definition
<?php
    function highlight ($string)
    {
        echo("<b><i>".strtoupper($string)."</i></b>");
    }

    $this_string = "warning";

    // This prints out WARNING in bold italic
    highlight ($this_string);
?>


Returning Values

A function can use the return statement to pass back values as in the example below.

Example of Returning a Value
<?php
    function add ($number_1, $number_2)
    {
        $result = $number_1 + $number_2;
        return ($result);
    }

    // This prints out 8
    echo (add (5, 3));
?>


Argument types aren't fixed until the function is called and the return type is determined only when it's actually returned.

Variable Scope

When a variable is created, its value is not automatically available at every point in the programme.

There is a relationship between where it is created and where it can be used. This relationship is called the variable's scope.

When a variable is created inside a function it only has scope inside the function. It only exists when the function is called and is discarded when the function ends.

Example of Scope
<?php
    function multiply ($number)
    {
        $result = $number * 2;
    }

    /* This doesn't print out anything because
    $result has no scope outside the function */
    $number = 10;
    multiply ($number);
    echo ($result);
?>


This is true even if the variable inside the function has the same name as one outside. Although they have the same name they are not the same variable as shown below.

Another Example of Scope
<?php
    function multiply ($number)
    {
        $number = $number * 2;
    }

    /* This prints out 10 because $result inside
    the function is different to $result outside */
    $number = 10;
    multiply ($number);
    echo ($number);
?>


Variables used within a function are local to the function with two exceptions.



Global Variables

If a variable is declared as global inside a function it means that it is the same as the variable outside the function.

Example of Global
<?php
    function multiply ($number)
    {
        global $number;
        $number = $number * 2;
    }

    /* This prints out 20 because $result inside
    the function is the same as $result outside */
    $number = 10;
    multiply ($number);
    echo ($number);
?>


Note: Global should only be used where absolutely necessary. When you give a function the right to alter a variable you pass a lot of power to the function.

When global is used in lots of functions in a large programme, it can be very difficult to remember which functions are changing a variable.


Passing Variables by Reference

By default only the value of a variable is passed to a function - not the variable itself.

But the variable may be passed by reference by using the & ampersand character before it.

This means that the variable outside the function with the same name is affected by what happens to the variable inside the function.

A Variable Passed by Reference
<?php
    function multiply (&$number)
    {
        $number = $number * 2;
    }

    /* This prints out 20 because $result inside
    the function is the same as $result outside */
    $number = 10;
    multiply ($number);
    echo ($number);
?>


Previous - PHP sorting arrays Previous - Sorting Arrays     Next - Include and Require Next - PHP include and require


Privacy | Terms | Contact | Links | Sitemap | RSS Feeds RSS and JavaScript Feeds
©2010 www.webdesignworkmate.co.uk all rights reserved 
Design and Production by smallbizonline website design © 2000-2010
Valid HTML 4.01! Level Double-A conformance icon, W3C-WAI Web Content Accessibility Guidelines 1.0Valid CSS!
PHPBasicsCreating a ScriptRunning a ScriptVariablesExpressions and OperatorsStringsStrings and SubstringsReplacing SubstringsRegular ExpressionsBranches and ConditionsLoopsArraysArray FunctionsSorting ArraysPHP user-defined functionsUser-Defined FunctionsInclude and RequireUploading FilesFile FunctionsSession Variables
Recommended Reading
PHP and MySQL web development

programming PHP

PHP cookbook
Tips and TricksPage TemplatesForm Reply ScriptsForm ValidationJavaScript to PHP
Got any PHP Tips?
Send me your tip and if it's suitable I'll put it on the site, credit it to you and add a link back to your site.