Page 110 - Open Soource Technologies 304.indd
P. 110

Unit 7: Functions



            Objectives                                                                            Notes

            After studying this unit, you will be able to:

               •  Discuss user defined functions.
               •  Explain function scope.
               •  Understand returning values by value.

               •  Declaring function parameters.
               •  Explain default parameters.
               •  Discuss static variables.

               •  Explain arrays.
               •  Discuss objects.

            Introduction


            A function in PHP can be built-in or user-defined; however, they are both called the same way.
            The general form of a function call is func(arg1,arg2,…). The number of  arguments varies from
            one function to another. Each argument be any valid expression, include other function calls.

            Here is a simple example of a predefined function:
                  Example:  $length = strlen(“Peter”);

                            strlen is a standard PHP function that returns the length of a string. Therefore,
                          $length is assigned the length of the string “Peter”: four.

                          Here’s an example of a function call being used as a function argument:
                  Example:  $length = strlen(strlen(“Peter”));
                            You  probably  already  guessed  the  result  of  this  example.  First,  the
                          innerstrlen(“Peter”) is executed, which results in the integer 4. So, the code
                          simpli-fies to
                          $length = strlen(4);
            Strlen ( ) expects a string and, therefore, (due to PHP’s magical auto conversion between types)
            converts the integer 4 to the string “4”, and thus, the resulting value of $length is 1, the length
            of “4”.

            7.1 User-Defined Functions

            The general way of defining a function is

                        function function_name (arg1, arg2, arg3, …)

                                  statement list
                                  }

            To return a value from a function, you need to make a call to return expr inside your function.
            This stops execution of the function and returns expr as the function’s value.



                                             LOVELY PROFESSIONAL UNIVERSITY                                   105
   105   106   107   108   109   110   111   112   113   114   115