Wednesday, 24 July 2019

PHP Functions

Creating PHP Function
<html>
      <head>
      <title>Writing PHP Function</title>
   </head>
      <body>
      <?php
         /* Defining a PHP Function */
         function writeMessage() {
            echo "You are really a nice person, Have a nice time!";
         }
         /* Calling a PHP Function */
         writeMessage();
      ?>
      </body>
</html>

PHP Functions with Parameters
<html>
   <head>
      <title>Writing PHP Function with Parameters</title>
   </head>
   <body>
      <?php
         function addFunction($num1, $num2) {
            $sum = $num1 + $num2;
            echo "Sum of the two numbers is : $sum";
         }
         addFunction(10, 20);
      ?>
   </body>
</html>

Passing Arguments by Reference
<html>
   <head>
      <title>Passing Argument by Reference</title>
   </head>
   <body>
      <?php
         function addFive($num) {
            $num += 5;
         }
         function addSix(&$num) {
            $num += 6;
         }
         $orignum = 10;
         addFive( $orignum );
         echo "Original Value is $orignum<br />";
         addSix( $orignum );
         echo "Original Value is $orignum<br />";
      ?>
   </body>
</html>
Output
Original Value is 10
Original Value is 16 

PHP Functions returning value
<html>
   <head>
      <title>Writing PHP Function which returns value</title>
   </head>
   <body>
      <?php
         function addFunction($num1, $num2) {
            $sum = $num1 + $num2;
            return $sum;
         }
         $return_value = addFunction(10, 20);
         echo "Returned value from the function : $return_value";
      ?>
   </body>
</html> 

0 comments

Post a Comment