PHP Tutorial

Your cool punch line

What is a PHP Function ?

You can think of a function as a machine. A machine takes the raw materials you feed it and works with them to achieve a purpose or to produce a product. A function accepts values from you, processes them, and then performs an action (printing to the browser, for example), returns a new value, or both.

A function is a self-contained block of code that can be called by your scripts. When called, the function's code is executed. You can pass values to functions, which will then work with them. When finished, a function can pass a value back to the calling code.

1). Creating Your PHP Functions
2). Calling Your PHP Functions
3). Use Parameters - Functions
4). Returning Values - Functions



Creating Your Functions

The general way of defining a function is

function function_name ()
{ statement list; }

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!

PHP Example:-

<?php
function bighello() {
echo "HELLO!";
} ?>
Go Top

Calling Your Functions

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 Example:-

<?php
bighello();
?>

Your out put is HELLO!

Go Top

Use Parameters - Functions

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 Example:-

<?php
function bighello($firstName){
    echo "Hello ". $firstName . "!";
} bighello('Raj');
?>

Your output is Hello Raj!

Go Top

Returning Values - Functions

A function can return a value using the return statement in conjunction with a value. The return statement stops the execution of the function and sends the value back to the calling code.

PHP Example:-

<?php
function addNums( $firstnumber, $secondnumber ) {
$result = $firstnumber + $secondnumber;
return $result;
}
echo addNums(2,5);
?>
Your output is " 7 " .

next

PHP Introduction

PHP Basic Development

PHP Control Structures

PHP Functions

PHP Arrays

PHP File System

Working With PHP Forms

PHP Classes And Objects

Introduction To Database

PHP Cookies

PHP Session

Computer SMS




© w3schoolas.com . All right reserved.www.w3schoolas.com Sitemap