SlideShare a Scribd company logo
Reusing Code and Writing Functions All about functions, arguments, passing by reference, globals and scope
Introduction This part will discuss about php function, arguments, globals and scope, with an efficient way structuring php program. This part teaches you how to build them (once), use them (many times), pass them arguments and have them return values, and generally make your scripts more compact, efficient and maintainable.
Why function? There are three important reasons why functions are a good.  First: user-defined functions allow you to separate your code into easily identifiable subsections - which are easier to understand and debug.  Second: functions make your program modular, allowing you to write a piece of code once and then re-use it multiple times within the same program.  Third: functions simplify code updates or changes, because the change needs only to be implemented in a single place (the function definition). Functions thus save time, money and electrons.
Example of function <?php  // define a function  function  myStandardResponse () {      echo  &quot;Get lost, jerk!<br /><br />&quot; ;  }  // on the bus  echo  &quot;Hey lady, can you spare a dime? <br />&quot; ;  myStandardResponse ();  ?> ----Output---- Hey lady, can you spare a dime?  Get lost, jerk!  Function myStandardResponse created. Invoke the function, by calling myStandardResponse().
Typical format for a function  function function_name (optional function arguments) {      statement 1...      statement 2...      .      .      .      statement n...  }
Arguments A function without an arguments will print the same value each time it being invoke. Putting some arguments will get the functions to return a different value each time they are invoked. .  Arguments work by using a placeholder to represent a certain variable within a function. Values for this variable are provided to the function at run-time from the main program. Since the input to the function will differ at each invocation, so will the output.
Example of arguments Function with one arguments <?php  // define a function  function  getCircumference ( $radius ) {      echo  &quot;Circumference of a circle with radius $radius is &quot; . sprintf ( &quot;%4.2f&quot; , ( 2  *  $radius  *  pi ())). &quot;<br />&quot; ;  }  // call a function with an argument  getCircumference ( 10 );  // call the same function with another argument  getCircumference ( 20 );  ?>   --output-- Circumference of a circle with radius 10 is 62.83 Circumference of a circle with radius 20 is 125.66 getCircumference() function is called with an argument. The argument is assigned to the placeholder variable $radius within the function, and then acted upon by the code within the function definition.
Function with more than one arguments <?php  // define a function  function  changeCase ( $str ,  $flag ) {       /* check the flag variable and branch the code */       switch( $flag ) {          case  'U' :    // change to uppercase               print  strtoupper ( $str ). &quot;<br />&quot; ;              break;          case  'L' :    // change to lowercase               print  strtolower ( $str ). &quot;<br />&quot; ;              break;          default:              print  $str . &quot;<br />&quot; ;              break;      }  }  // call the function  changeCase ( &quot;The cow jumped over the moon&quot; ,  &quot;U&quot; );  changeCase ( &quot;Hello Sam&quot; ,  &quot;L&quot; );  ?>   --output— THE COW JUMPED OVER THE MOON hello sam
In the previous script, we also can pass more than one arguments to the function. Depending on the value of the second argument, program flow within the function moves to the appropriate branch and manipulates the first argument.
Return a value The functions on the previous page simply printed their output to the screen.  But what if you want the function to do something else with the result? In PHP, you can have a function return a value, such as the result of a calculation, to the statement that called it.  This is done using a  return  statement within the function.
Examples <?php  // define a function  function  getCircumference ( $radius ) {       // return value       return ( 2  *  $radius  *  pi ());  }  /* call a function with an argument and store the result in a variable */  $result  =  getCircumference ( 10 );  /* call the same function with another argument and print the return value */  print  getCircumference ( 20 );  ?>   --output— 125.663706144  The argument passed to the getCircumference() function is processed, and the result is returned to the main program, where it may be captured in a variable, printed, or dealt with in other ways.
Examples cont….. Use the result of a function inside another function  <?php  // define a function  function  getCircumference ( $radius ) {  // return value       return ( 2  *  $radius  *  pi ());  }  // print the return value after formatting it  print  &quot;The answer is &quot; . sprintf ( &quot;%4.2f&quot; ,  getCircumference ( 20 ));  ?>   --output— The answer is 125.66
Examples cont….. A function can just as easily return an array <?php  /* define a function that can accept a list of email addresses */  function  getUniqueDomains ( $list ) {       /* iterate over the list, split addresses and add domain part to another array */       $domains  = array();      foreach ( $list  as  $l ) {           $arr  =  explode ( &quot;@&quot; ,  $l );           $domains [] =  trim ( $arr [ 1 ]);      }       // remove duplicates and return       return  array_unique ( $domains );  }  // read email addresses from a file into an array  $fileContents  =  file ( &quot;data.txt&quot; );  /* pass the file contents to the function and retrieve the result array */  $returnArray  =  getUniqueDomains ( $fileContents );  // process the return array  foreach ( $returnArray  as  $d ) {      print  &quot;$d, &quot; ;  }  ?>   data.txt: [email_address] [email_address] [email_address] --output— yahoo.com, hotmail.com, cosmopoint.com,
Marching arguments order Order in which arguments are passed to a function can be important. It will affect the value that will pass to the variables in function.
Examples of argument order <?php  // define a function  function  introduce ( $name ,  $place ) {      print  &quot;Hello, I am $name from $place&quot; ;  }  // call function  introduce ( &quot;Moonface&quot; ,  &quot;The Faraway Tree&quot; );  ?>   The first value ‘Moonface’ will assign to the $name, while the “The Faraway Tree” will assign to the $place.
Examples cont….. The output:  introduce ( &quot;Moonface&quot; ,  &quot;The Faraway Tree&quot; ); Hello, I am Moonface from The Faraway Tree  If you reversed the order in which arguments were passed to the function introduce ( &quot;The Faraway Tree Moonface&quot; ,  &quot;Moonface&quot; ); Hello, I am The Faraway Tree from Moonface  If forgot to pass a required argument altogether  Warning: Missing argument 2 for introduce() in xx.php on line 3 Hello, I am Moonface from
Default value for arguments In order to avoid such errors, PHP allows the user to specify default values for all the arguments in a user-defined function. These default values are used if the function invocation is missing some arguments.
Examples <?php  // define a function  function  introduce ( $name = &quot;John Doe&quot; ,  $place = &quot;London&quot; ) {      print  &quot;Hello, I am $name from $place&quot; ;  }  // call function  introduce ( &quot;Moonface&quot; );  ?> ---Output Hello, I am Moonface from London The function has been called with only a single argument, even though the function definition requires two. New value will overwrite the default value, while the missing arguments will used the default value.
Function functions  All the examples on the previous page have one thing in common: the number of arguments in the function definition is fixed.  PHP 4.x also supports variable-length argument lists, by using the  func_num_args()  and  func_get_args()  commands.  These functions are called &quot;function functions&quot;.
Example <?php  // define a function  function  someFunc () {       // get the number of arguments passed       $numArgs  =  func_num_args ();      // get the arguments       $args  =  func_get_args ();       // print the arguments       print  &quot;You sent me the following arguments: &quot; ;      for ( $x  =  0 ;  $x  <  $numArgs ;  $x ++) {          print  &quot;<br />Argument $x: &quot; ;           /* check if an array was passed and, if so, iterate and print contents */           if ( is_array ( $args [ $x ])) {              print  &quot; ARRAY &quot; ;              foreach ( $args [ $x ] as  $index  =>  $element ) {                  print  &quot; $index => $element &quot; ;              }          }          else {              print  &quot; $args[$x] &quot; ;          }      }  }  // call a function with different arguments  someFunc ( &quot;red&quot; ,  &quot;green&quot; ,  &quot;blue&quot; , array( 4 , 5 ),  &quot;yellow&quot; );  ?>   --output-- You sent me the following arguments:  Argument 0: red  Argument 1: green  Argument 2: blue  Argument 3: ARRAY 0 => 4 1 => 5  Argument 4: yellow
Globals The  global  command allows the variable to be used outside the function after the function being invoked. To have variables within a function accessible from outside it (and vice-versa), declare the variables as &quot; global &quot;
Example Without  global  command <?php   // define a variable in the main program  $today  =  &quot;Tuesday&quot; ;  // define a function  function  getDay () {       // define a variable inside the function       $today  =  &quot;Saturday&quot; ;       // print the variable       print  &quot;It is $today inside the function<br />&quot; ;  }  // call the function  getDay ();  // print the variable  print  &quot;It is $today outside the function&quot; ;  ?>   --output— It is Saturday inside the function It is Tuesday outside the function
Example cont… With a  global  command <?php  // define a variable in the main program  $today  =  &quot;Tuesday&quot; ;  // define a function  function  getDay () {       // make the variable global       global  $today ;             // define a variable inside the function       $today  =  &quot;Saturday&quot; ;       // print the variable       print  &quot;It is $today inside the function<br />&quot; ;  }  // print the variable  print  &quot;It is $today before running the function<br />&quot; ;  // call the function  getDay ();  // print the variable  print  &quot;It is $today after running the function&quot; ;  ?>   ----output--- It is Tuesday before running the function It is Saturday inside the function It is Saturday after running the function
Passing by value and reference There are two method in passing the arguments either by value or by reference. Passing arguments to a function &quot;by value&quot; - meaning that a copy of the variable was passed to the function, while the original variable remained untouched. PHP also allows method to pass &quot;by reference&quot; - meaning that instead of passing a value to a function, it pass a reference (pointer) to the original variable, and have the function act on that instead of a copy.
Passing by value Example 1 <?php  // create a variable  $today  =  &quot;Saturday&quot; ;  // function to print the value of the variable  function  setDay ( $day ) {       $day  =  &quot;Tuesday&quot; ;      print  &quot;It is $day inside the function<br />&quot; ;  }  // call function  setDay ( $today );  // print the value of the variable  print  &quot;It is $today outside the function&quot; ;  ?>   --output— It is Tuesday inside the function It is Saturday inside the function
Passing by reference Example 2 <?php  // create a variable  $today  =  &quot;Saturday&quot; ;  // function to print the value of the variable  function  setDay (& $day ) {       $day  =  &quot;Tuesday&quot; ;      print  &quot;It is $day inside the function<br />&quot; ;  }  // call function  setDay ( $today );  // print the value of the variable  print  &quot;It is $today outside the function&quot; ;  ?>   --output— It is Tuesday inside the function It is Tuesday outside the function
Example 1 : The getDay() function is invoked, it passes the value &quot;Saturday&quot; to the function (&quot;passing by value&quot;). The original variable remains untouched; only its content is sent to the function. The function then acts on the content, modifying and displaying it. Example 2: Notice the ampersand (&) before the argument in the function definition. This tells PHP to use the variable reference instead of the variable value. When such a reference is passed to a function, the code inside the function acts on the reference, and modifies the content of the original variable (which the reference is pointing to) rather than a copy.
The discussion about variables would be incomplete without mentioning the two ways of passing variables. This, of course, is what the global keyword does inside a function: use a reference to ensure that changes to the variable inside the function also reflect outside it.  The PHP manual puts it best when it says &quot;...when you declare a variable as global $var you are in fact creating a reference to a global variable.

More Related Content

Php Reusing Code And Writing Functions

  • 1. Reusing Code and Writing Functions All about functions, arguments, passing by reference, globals and scope
  • 2. Introduction This part will discuss about php function, arguments, globals and scope, with an efficient way structuring php program. This part teaches you how to build them (once), use them (many times), pass them arguments and have them return values, and generally make your scripts more compact, efficient and maintainable.
  • 3. Why function? There are three important reasons why functions are a good. First: user-defined functions allow you to separate your code into easily identifiable subsections - which are easier to understand and debug. Second: functions make your program modular, allowing you to write a piece of code once and then re-use it multiple times within the same program. Third: functions simplify code updates or changes, because the change needs only to be implemented in a single place (the function definition). Functions thus save time, money and electrons.
  • 4. Example of function <?php // define a function function myStandardResponse () {     echo &quot;Get lost, jerk!<br /><br />&quot; ; } // on the bus echo &quot;Hey lady, can you spare a dime? <br />&quot; ; myStandardResponse (); ?> ----Output---- Hey lady, can you spare a dime? Get lost, jerk! Function myStandardResponse created. Invoke the function, by calling myStandardResponse().
  • 5. Typical format for a function function function_name (optional function arguments) {     statement 1...     statement 2...     .     .     .     statement n... }
  • 6. Arguments A function without an arguments will print the same value each time it being invoke. Putting some arguments will get the functions to return a different value each time they are invoked. . Arguments work by using a placeholder to represent a certain variable within a function. Values for this variable are provided to the function at run-time from the main program. Since the input to the function will differ at each invocation, so will the output.
  • 7. Example of arguments Function with one arguments <?php // define a function function getCircumference ( $radius ) {     echo &quot;Circumference of a circle with radius $radius is &quot; . sprintf ( &quot;%4.2f&quot; , ( 2 * $radius * pi ())). &quot;<br />&quot; ; } // call a function with an argument getCircumference ( 10 ); // call the same function with another argument getCircumference ( 20 ); ?> --output-- Circumference of a circle with radius 10 is 62.83 Circumference of a circle with radius 20 is 125.66 getCircumference() function is called with an argument. The argument is assigned to the placeholder variable $radius within the function, and then acted upon by the code within the function definition.
  • 8. Function with more than one arguments <?php // define a function function changeCase ( $str , $flag ) {      /* check the flag variable and branch the code */      switch( $flag ) {         case 'U' : // change to uppercase              print strtoupper ( $str ). &quot;<br />&quot; ;             break;         case 'L' : // change to lowercase              print strtolower ( $str ). &quot;<br />&quot; ;             break;         default:             print $str . &quot;<br />&quot; ;             break;     } } // call the function changeCase ( &quot;The cow jumped over the moon&quot; , &quot;U&quot; ); changeCase ( &quot;Hello Sam&quot; , &quot;L&quot; ); ?> --output— THE COW JUMPED OVER THE MOON hello sam
  • 9. In the previous script, we also can pass more than one arguments to the function. Depending on the value of the second argument, program flow within the function moves to the appropriate branch and manipulates the first argument.
  • 10. Return a value The functions on the previous page simply printed their output to the screen. But what if you want the function to do something else with the result? In PHP, you can have a function return a value, such as the result of a calculation, to the statement that called it. This is done using a return statement within the function.
  • 11. Examples <?php // define a function function getCircumference ( $radius ) {      // return value      return ( 2 * $radius * pi ()); } /* call a function with an argument and store the result in a variable */ $result = getCircumference ( 10 ); /* call the same function with another argument and print the return value */ print getCircumference ( 20 ); ?> --output— 125.663706144 The argument passed to the getCircumference() function is processed, and the result is returned to the main program, where it may be captured in a variable, printed, or dealt with in other ways.
  • 12. Examples cont….. Use the result of a function inside another function <?php // define a function function getCircumference ( $radius ) { // return value      return ( 2 * $radius * pi ()); } // print the return value after formatting it print &quot;The answer is &quot; . sprintf ( &quot;%4.2f&quot; , getCircumference ( 20 )); ?> --output— The answer is 125.66
  • 13. Examples cont….. A function can just as easily return an array <?php /* define a function that can accept a list of email addresses */ function getUniqueDomains ( $list ) {      /* iterate over the list, split addresses and add domain part to another array */      $domains = array();     foreach ( $list as $l ) {          $arr = explode ( &quot;@&quot; , $l );          $domains [] = trim ( $arr [ 1 ]);     }      // remove duplicates and return      return array_unique ( $domains ); } // read email addresses from a file into an array $fileContents = file ( &quot;data.txt&quot; ); /* pass the file contents to the function and retrieve the result array */ $returnArray = getUniqueDomains ( $fileContents ); // process the return array foreach ( $returnArray as $d ) {     print &quot;$d, &quot; ; } ?> data.txt: [email_address] [email_address] [email_address] --output— yahoo.com, hotmail.com, cosmopoint.com,
  • 14. Marching arguments order Order in which arguments are passed to a function can be important. It will affect the value that will pass to the variables in function.
  • 15. Examples of argument order <?php // define a function function introduce ( $name , $place ) {     print &quot;Hello, I am $name from $place&quot; ; } // call function introduce ( &quot;Moonface&quot; , &quot;The Faraway Tree&quot; ); ?> The first value ‘Moonface’ will assign to the $name, while the “The Faraway Tree” will assign to the $place.
  • 16. Examples cont….. The output: introduce ( &quot;Moonface&quot; , &quot;The Faraway Tree&quot; ); Hello, I am Moonface from The Faraway Tree If you reversed the order in which arguments were passed to the function introduce ( &quot;The Faraway Tree Moonface&quot; , &quot;Moonface&quot; ); Hello, I am The Faraway Tree from Moonface If forgot to pass a required argument altogether Warning: Missing argument 2 for introduce() in xx.php on line 3 Hello, I am Moonface from
  • 17. Default value for arguments In order to avoid such errors, PHP allows the user to specify default values for all the arguments in a user-defined function. These default values are used if the function invocation is missing some arguments.
  • 18. Examples <?php // define a function function introduce ( $name = &quot;John Doe&quot; , $place = &quot;London&quot; ) {     print &quot;Hello, I am $name from $place&quot; ; } // call function introduce ( &quot;Moonface&quot; ); ?> ---Output Hello, I am Moonface from London The function has been called with only a single argument, even though the function definition requires two. New value will overwrite the default value, while the missing arguments will used the default value.
  • 19. Function functions All the examples on the previous page have one thing in common: the number of arguments in the function definition is fixed. PHP 4.x also supports variable-length argument lists, by using the func_num_args() and func_get_args() commands. These functions are called &quot;function functions&quot;.
  • 20. Example <?php // define a function function someFunc () {      // get the number of arguments passed      $numArgs = func_num_args ();     // get the arguments      $args = func_get_args ();      // print the arguments      print &quot;You sent me the following arguments: &quot; ;     for ( $x = 0 ; $x < $numArgs ; $x ++) {         print &quot;<br />Argument $x: &quot; ;          /* check if an array was passed and, if so, iterate and print contents */          if ( is_array ( $args [ $x ])) {             print &quot; ARRAY &quot; ;             foreach ( $args [ $x ] as $index => $element ) {                 print &quot; $index => $element &quot; ;             }         }         else {             print &quot; $args[$x] &quot; ;         }     } } // call a function with different arguments someFunc ( &quot;red&quot; , &quot;green&quot; , &quot;blue&quot; , array( 4 , 5 ), &quot;yellow&quot; ); ?> --output-- You sent me the following arguments: Argument 0: red Argument 1: green Argument 2: blue Argument 3: ARRAY 0 => 4 1 => 5 Argument 4: yellow
  • 21. Globals The global command allows the variable to be used outside the function after the function being invoked. To have variables within a function accessible from outside it (and vice-versa), declare the variables as &quot; global &quot;
  • 22. Example Without global command <?php // define a variable in the main program $today = &quot;Tuesday&quot; ; // define a function function getDay () {      // define a variable inside the function      $today = &quot;Saturday&quot; ;      // print the variable      print &quot;It is $today inside the function<br />&quot; ; } // call the function getDay (); // print the variable print &quot;It is $today outside the function&quot; ; ?> --output— It is Saturday inside the function It is Tuesday outside the function
  • 23. Example cont… With a global command <?php // define a variable in the main program $today = &quot;Tuesday&quot; ; // define a function function getDay () {      // make the variable global      global $today ;           // define a variable inside the function      $today = &quot;Saturday&quot; ;      // print the variable      print &quot;It is $today inside the function<br />&quot; ; } // print the variable print &quot;It is $today before running the function<br />&quot; ; // call the function getDay (); // print the variable print &quot;It is $today after running the function&quot; ; ?> ----output--- It is Tuesday before running the function It is Saturday inside the function It is Saturday after running the function
  • 24. Passing by value and reference There are two method in passing the arguments either by value or by reference. Passing arguments to a function &quot;by value&quot; - meaning that a copy of the variable was passed to the function, while the original variable remained untouched. PHP also allows method to pass &quot;by reference&quot; - meaning that instead of passing a value to a function, it pass a reference (pointer) to the original variable, and have the function act on that instead of a copy.
  • 25. Passing by value Example 1 <?php // create a variable $today = &quot;Saturday&quot; ; // function to print the value of the variable function setDay ( $day ) {      $day = &quot;Tuesday&quot; ;     print &quot;It is $day inside the function<br />&quot; ; } // call function setDay ( $today ); // print the value of the variable print &quot;It is $today outside the function&quot; ; ?> --output— It is Tuesday inside the function It is Saturday inside the function
  • 26. Passing by reference Example 2 <?php // create a variable $today = &quot;Saturday&quot; ; // function to print the value of the variable function setDay (& $day ) {      $day = &quot;Tuesday&quot; ;     print &quot;It is $day inside the function<br />&quot; ; } // call function setDay ( $today ); // print the value of the variable print &quot;It is $today outside the function&quot; ; ?> --output— It is Tuesday inside the function It is Tuesday outside the function
  • 27. Example 1 : The getDay() function is invoked, it passes the value &quot;Saturday&quot; to the function (&quot;passing by value&quot;). The original variable remains untouched; only its content is sent to the function. The function then acts on the content, modifying and displaying it. Example 2: Notice the ampersand (&) before the argument in the function definition. This tells PHP to use the variable reference instead of the variable value. When such a reference is passed to a function, the code inside the function acts on the reference, and modifies the content of the original variable (which the reference is pointing to) rather than a copy.
  • 28. The discussion about variables would be incomplete without mentioning the two ways of passing variables. This, of course, is what the global keyword does inside a function: use a reference to ensure that changes to the variable inside the function also reflect outside it. The PHP manual puts it best when it says &quot;...when you declare a variable as global $var you are in fact creating a reference to a global variable.