What are some best practices for structuring PHP functions and handling parameters to ensure efficient and reusable code?

When structuring PHP functions, it is important to follow best practices to ensure efficient and reusable code. One way to achieve this is by properly defining and handling function parameters. This includes using type declarations, default parameter values, and parameter validation to ensure the function receives the correct input. By structuring functions in a clear and organized manner, you can improve code readability and maintainability.

// Example of a well-structured PHP function with parameter handling

function calculateTotal(int $quantity, float $price, string $currency = 'USD'): string {
    // Validate parameters
    if ($quantity <= 0 || $price <= 0) {
        throw new InvalidArgumentException('Quantity and price must be greater than zero.');
    }

    // Calculate total amount
    $total = $quantity * $price;

    // Format total amount with currency symbol
    $formattedTotal = $currency . number_format($total, 2);

    return $formattedTotal;
}

// Example usage of the function
echo calculateTotal(5, 10.50); // Output: USD52.50