Current Location: Home> Latest Articles> PHP Function Parameters Explained: Types, Passing Methods, and Default Values

PHP Function Parameters Explained: Types, Passing Methods, and Default Values

M66 2025-10-20

Understanding PHP Function Parameters and Their Types

In PHP, function parameters can be defined and passed in several ways. The most common methods include passing by value, passing by reference, and using default parameter values. Each approach affects how variables behave inside and outside the function.

Pass by Value (Default)

Passing by value is the default behavior in PHP. In this mode, the function receives a copy of the variable, meaning changes inside the function will not affect the original variable.

function sum($a, $b) {
    $a += $b;
}

In this example, modifying $a inside the function does not change the variable outside the function.

Pass by Reference

If you want a function to modify the original variable directly, you can pass it by reference by adding an ampersand (&) before the parameter name.

function increment(&$a) {
    $a++;
}

In this case, any change to $a inside the function will be reflected outside of it as well.

Default Parameter Values

PHP allows you to set default values for parameters. If no value is provided when calling the function, the default will be used automatically.

function greet($name = "World") {
    echo "Hello, $name!";
}

Calling greet() will output “Hello, World!”, while greet("Alice") will output “Hello, Alice!”.

Parameter Type Declarations

Starting with PHP 7, you can declare parameter types to ensure the correct data type is passed into a function. Common types include:

  • Primitive types: int, float, string, bool
  • Complex types: array, object
  • Nullable types: Add a ? before the type to allow either that type or null

Examples of Parameter Type Declarations

function formatDate(DateTime $date) {
    // Work with DateTime object
}

function avg(int $a, int $b): float {
    return ($a + $b) / 2;
}

In the above code, the formatDate() function requires a DateTime object, while avg() expects integer parameters and returns a float.

Practical Example: Value vs Reference Passing

function doubleValue($value) {
    $value *= 2;
}

$x = 10;
doubleValue($x);  // $x remains unchanged because it’s passed by value
echo $x;  // Outputs 10

function doubleValueByRef(&$value) {
    $value *= 2;
}

doubleValueByRef($x);  // $x is modified because it’s passed by reference
echo $x;  // Outputs 20

This comparison demonstrates that passing by reference allows a function to modify external variables, which is useful in scenarios requiring synchronized variable updates.

Conclusion

PHP’s flexible parameter passing and type declaration features provide developers with strong control over function behavior. By properly using value passing, reference passing, and type hints, you can write more robust, maintainable, and error-resistant PHP code.