Creating a Simple Function

In this section, we are going to create a simple function that will calculate the discount of a given percentage. To do this, follow these steps:

  1. Open your code editor and create a new file, function.php.
  2. Within the new file, create your open and close php tags:
    <?php
    ?>
  3. Now, we are going to create two new variables: $sweaterPrice and $precentOff. They will store the original price of the product, as well as the percent off:
    <?php
    $sweaterPrice = 50;
    $percentOff = 0.25;
    ?>
  4. Now that we have our variables, we can define our function. Our function is simple; it accepts a price and discount percentage. Inside of the function, we multiply the price by the discount percentage and return the product:
    <?php
       $sweaterPrice = 50;
        $percentOff = 0.25;
    
        function couponCode($price, $discount){
            return $price * $discount;
        }
    ?>
  5. Finally, we can go ahead and print our message about the discount to our users, using our newly created function:
    <?php
    
        $sweaterPrice = 50;
        $percentOff = 0.25;
    
        function couponCode($price, $discount){
            return $price * $discount;
        }
        echo "The sweater originally costs $" . $sweaterPrice . " with the discount you'll pay $" . ($sweaterPrice - couponCode($sweaterPrice, $percentOff)) . "
    ";
    ?>

Now that you have an understanding of functions, you should be comfortable with developing reusable code and applying them. In the next section, we will learn about classes. Classes will give us a better understanding of structuring code and properties into a neat package.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset