"Welcome to our PHP 101 blog, where we demystify the world of web development. "

Monday, January 22, 2024

User-Defined Function with Default Parameter:

User-Defined Function with Default Parameter:

In PHP, a User-Defined Function with Default Parameters allows you to define default values for one or more parameters in the function declaration. If a value is not provided for a parameter during the function call, the default value is used. This feature enhances the flexibility of the function by providing reasonable default values while allowing customization when needed.

Example:

// User-Defined Function with Default Parameter

function greetUser($name = "Guest") {

    echo "Hello, $name!";

}

// Calling the function without providing a name

greetUser(); 

// Output: Hello, Guest!

// Calling the function with a specific name

greetUser("John"); 

// Output: Hello, John!

In this example, the greetUser function has a parameter $name with a default value of "Guest". When the function is called without providing a value for $name, it uses the default value, resulting in a greeting for a guest. If a specific name is provided during the function call, that name is used instead.


Key Points:

Default Parameter Syntax:

function functionName($param1, $param2 = defaultValue, $param3, ...) {

    // Function body

}

Default Parameters must be at the end:

If a function has parameters with default values, they must be placed at the end of the parameter list. Non-default parameters cannot follow default parameters.


Providing Values during Function Call:

When calling a function with default parameters, you can either provide values for all parameters or only for the ones you want to override. If a value is provided during the call, it takes precedence over the default value.


No comments:

Post a Comment

Pages

SoraTemplates

Best Free and Premium Blogger Templates Provider.

Buy This Template