comp 205 - week 6 dr. chunbo chu. functions the real power of php: more than 700 built-in functions....

71
PHP: Hyper-text Preprocessor COMP 205 - Week 6 Dr. Chunbo Chu

Upload: marybeth-merritt

Post on 25-Dec-2015

216 views

Category:

Documents


1 download

TRANSCRIPT

  • Slide 1
  • COMP 205 - Week 6 Dr. Chunbo Chu
  • Slide 2
  • Functions The real power of PHP: more than 700 built-in functions. To keep the browser from executing a script when the page loads, you can put your script into a function. A function will be executed by a call to the function. You may call a function from anywhere within a page.
  • Slide 3
  • Create a PHP Function A function will be executed by a call to the function. function functionName() { code to be executed; }
  • Slide 4 ">
  • Adding parameters "; } echo "My name is "; writeName("Kai Jim"); echo "My sister's name is "; writeName("Hege"); echo "My brother's name is "; writeName("Stale"); ?>
  • Slide 5
  • Return values
  • Slide 6
  • Common error I: invoking an undefined function function output_paragraph( $text ) { echo " {$text} "; } outputParagraph( 'Today is '. Date('d/m/y') );
  • Slide 7
  • Common error II: scope function get_circle_area() { return 3.14 * $radius * $radius; } $radius = 5; $area = get_circle_area(); echo " The area of the circle is {$area} ";
  • Slide 8
  • function get_circle_circumference( $diameter ) { $circumference = 3.14 * $diameter; } echo ' '; echo 'The circumference is '; get_circle_circumference( 10 ); echo $circumference; echo ' ';
  • Slide 9
  • Variables in PHP If you do not use functions, any variables you create can be used anywhere in your script But if you define your own functions, you must distinguish four kinds of variable a function's formal parameters a function's local variables your script's global variables PHP's superglobal variables These differ in where they are created which hence determines their scope The scope of a variable is the range of statements in the program in which the variable's name is known
  • Slide 10
  • Formal parameters and local variables A function's formal parameters as we know, these are created when the function is invoked scope: the function's body A function's local variables variables which are created inside a function scope: from the statement in which they are created to the end of the function's body
  • Slide 11
  • Global variables and superglobal variables A script's global variables variables which are created outside a function scope: from the statement in which they are created to the end of the script but not inside functions PHP's superglobal variables, e.g. $_GET, $_POST as we have seen, these are special PHP variables which you don't create scope: the whole script, both inside and outside functions
  • Slide 12
  • What is the output? $x = 10; function func1() { echo $x; } func1();
  • Slide 13