PHP I : Functions

PHP Function Refence:
http://www.php.net/manual/en/funcref.php

Follow this lesson in Ullman Chapter 10. The scripts are located in the 10 directory.

 

Creating and Calling a User-Defined Function

function function_name () {
  #do stuff here
}

Function names are case-insensitive!

For example:

<?php
function my_first_function() {
for($i = 0; $i < 10; $i++) {
  echo “This is iteration $i. <br />”;
}
}

echo “Here’s where we call my_first_function: <br />”;
my_first_function();
echo “The function has completed.”;
?>

 

Checking That a Function Exists

if (function_exists(‘my_first_function’)) {
….
}

 

Using Arguments

function function_name (argument1, argument2, …) {
  #do stuff here
}

For example:

<?php
function my_arguments_function($user_name, $user_title) {
echo “Hi, $user_name.<br />”;
echo “You are a(n) $user_title.<br />”;
}

echo “Here’s where we call my_arguments_function: <br />”;
my_arguments_function(‘Fred’, ‘Antihero’);
echo “The function has completed.”;
?>

 

Default Argument Values

<?php
// Notice that if no message is passed,
// “Hi there” is used by default:

function my_defaults_function ($count, $msg = “Hi there.”) {
for($i = 0; $i < $count; $i++){
  echo “Saying: $msg for repetition: $i .”<br />”;
}
}
echo “Print it 3 times ….<br />”;
my_defaults_function (3, “Hello”);
?>

Default argument values, if there are any, must be named last! This has the benefit of making them optional.

 

Return Values

Use the return statement:

function function_name ($arg1) {
  statements();
  return $value
;
}

For instance:

function my_calculator ($quantity, $price) {

// Calculate:
$total = $quantity * $price;
// Format:
$total = number_format ($total, 2);

// Return the value:
return $total;

}

Then use it like this:

$sale_total = my_calculator ($order_qty, $sale_price);

 

Variable Scope

A variable you declare within a function is local to that function. It isn’t available elsewhere.

Variables declared using global are exactly that: available globally, both within and outside of particular functions.

Environment variables (like $_SERVER[‘PHP_SELF’]) are available not just to your PHP environment, but to everyone’s.

To use a global variable, declare it early in your script, outside any function:

$tax_rate = 6.875;

Then you can make this declaration within a function:

global $tax_rate;

Your script will use the external (global) variable, as long as it exists outside the function.

 

To do out of class:

Review Chapter 10 of Ullman.