Get your own free workspace
View
 

Functions_php

Page history last edited by Mike Leishman 4 years, 10 months ago

 Functions

 

http://www.php.net/manual/en/language.functions.php

 

Functions in PHP can work in two ways.

 

The first is such that the body appears like a small program in its own right in the same way that a procedure would be used in another language such as Pascal.

 

The second is when the function works in the same manner as the inbuilt functions. So for example, I could define a function named Add1 so I could use it in a statement where a variable was assigned the value returned from the function. eg $newnumber = Add1($oldnumber);

 

Function arguments are normally passed by value (the original values are not changed by what happens in the function) but this can be changed to "by refererence" to enable values to be returned if required.

 

Functions as Procedures

 

This function returns the area of a circle by reference. It is typical of the use of a procedure where parameter values are passed in and out of the procedure.

 

<?php

//Calculate area of a circle in PHP and designed for use at the command line

function Area_Circle($r, &$a) //$r is passed in by value; $a is passed out by reference

   fwrite(STDOUT, "Area of Circle calculator. \n");

  {

     $a = 3.14 * $r * $r;

  }

 

//main body 

fwrite(STDOUT, "Enter the radius of the circle  -> ");

fscanf(STDIN, "%d\n", $radius);

Area_Circle($radius, $area); //Call to the function

fwrite(STDOUT, "The area of the circle is ".$area."\n");

exit(0);

?>

 

Functions as Functions

 

This function returns the area of a circle. It is typical of the use of a function that represents a value and where the function can programaticaly be treated much like a variable.

 

<?php

//Calculate area of a circle in PHP and designed for use at the command line

function Area_Circle($r)

  {

   $a = 3.14 * $r * $r;

   return $a;

  }

fwrite(STDOUT, "Area of Circle calculator. \n"); 

fwrite(STDOUT, "Enter the radius of the circle  -> ");

fscanf(STDIN, "%d\n", $radius);

fwrite(STDOUT, "The area of the circle is ".Area_Circle($radius)."\n");

exit(0);

?>

 

Exercises

  1. Two functions are created that accepts two values as parameters. The functions will determine which is the bigger and which is the smaller value. The program then calls these functions and displays the larger value followed by the smaller value. Test your program with both numbers and strings.
  2. Write a function that will accept the date in dd/mm/yyyy format and return it in three different fields of dd Month and yyyy. ie 12/03/2001 would return 12  March 2001 as three separate fields.
  3. Extend exercise 2 to return the date entered in the form Day-DD Month and yyyy ( ie 12/03/2001) and to return Sunday 12 March 2001 as four separate fields. 

 

 

Comments (0)

You don't have permission to comment on this page.