Monday 20 January 2014

A complete PHP Tutorial For Beginners To Learn PHP Basic Part 4


    • PHP Function

    • Create a PHP Function

        Syntax

        1. function functionName() 
        2. code to be executed; 
        3. }
        • Give the function a name that reflects what the function does
        • The function name can start with a letter or underscore (not a number)
        • Example

          • A simple function that writes my name when it is called:
          1. <html> 
          2. <body> 
          3. <?php 
          4. function writeName() 
          5. echo "JYOTI"; 
          6. echo "My name is "; writeName(); 
          7. ?> 
          8. </body> 
          9. </html>

          • Output:

          1. My name is JYOTI
    • PHP Functions - Adding parameters


      • To add more functionality to a function, we can add parameters. A parameter is just like a variable. Parameters are specified after the function name, inside the parentheses.
      • Example 1

        • The following example will write different first names, but equal last name:
        1. <html> 
        2. <body> 
        3. <?php 
        4. function writeName($fname) 
        5. echo $fname . " BISWAS.<br />"; 
        6. echo "My name is "; writeName("JYOTIRMOY"); 
        7. echo "My sister's name is "; writeName("Hege"); 
        8. echo "My brother's name is "; writeName("Stale"); 
        9. ?> 
        10. </body> 
        11. </html>
        12. Output:
        13. My name is JYOTIRMOY BISWAS.

    • PHP Functions - Return values


    • To let a function return a value, use the return statement.

      • Example

        • Output
        • 1+16=17
        1. <html> 
        2. <body> 
        3. <?php function add($x,$y) 
        4. $total=$x+$y; return $total; 
        5. echo "1 + 16 = " . add(1,16); 
        6. ?> 
        7. </body> 
        8. </html>

No comments :

Post a Comment