Bird
0
0

You want to create a function that calculates the total price with tax. The tax rate should default to 0.2 (20%) if not provided. Which function definition is correct?

hard📝 Application Q8 of 15
PHP - Functions
You want to create a function that calculates the total price with tax. The tax rate should default to 0.2 (20%) if not provided. Which function definition is correct?
Afunction totalPrice($price, $tax) { return $price * (1 + $tax); }
Bfunction totalPrice($tax = 0.2, $price) { return $price * (1 + $tax); }
Cfunction totalPrice($price, $tax = 0.2) { return $price * (1 + $tax); }
Dfunction totalPrice($price = 0.2, $tax) { return $price * (1 + $tax); }
Step-by-Step Solution
Solution:
  1. Step 1: Identify parameter order rules

    Parameters with defaults must come after those without defaults.
  2. Step 2: Check each function signature

    function totalPrice($price, $tax = 0.2) { return $price * (1 + $tax); } has required $price first, then default $tax (correct). function totalPrice($tax = 0.2, $price) { return $price * (1 + $tax); } and D have default before required (invalid). function totalPrice($price, $tax) { return $price * (1 + $tax); } has no default for $tax (not meeting requirement).
  3. Final Answer:

    function totalPrice($price, $tax = 0.2) { return $price * (1 + $tax); } -> Option C
  4. Quick Check:

    Correct parameter order with default value [OK]
Quick Trick: Put required parameters first, defaults last [OK]
Common Mistakes:
  • Placing default parameters before required ones
  • Omitting default value for optional parameters
  • Confusing parameter order

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes