Functions & Type Hints

🐘 PHP Lesson 7 Beginner

Functions organize reusable logic blocks. In modern PHP, you can declare parameter and return types explicitly using type hints to enforce type safety.

1 Pass-by-Reference (&) and Type Hints

Functions accept inputs and return values:

  • Pass-by-Reference (`&$x`): Prepending an ampersand to a parameter allows the function to modify the caller's variable directly.
  • Type Hints (PHP 7/8): You can declare the data types of arguments and return values explicitly to prevent bugs: `function add(int $a): int {}`.
2 Functions Code

Let's run a program illustrating functions, default arguments, and type hints:

PHP — Functions ▶ Run Code
<?php
// Function with type hints (PHP 7/8+)
function calculatePrice(float $price, float $taxRate = 0.08): float {
    return $price + ($price * $taxRate);
}

// Pass-by-reference using ampersand
function doubleValue(int &$number) {
    $number *= 2;
}

$total = calculatePrice(100.0);
echo "Total Price: $" . $total . "\n";

$value = 25;
doubleValue($value);
echo "Doubled Value: " . $value . "\n"; // Output is 50
?>
3 Code Challenge
Challenge: Write a method called `divide` with type hints that accepts two integers and returns a float. Add checks to return `0.0` if the divisor is zero.