Tuesday, March 05, 2013

Default Parameters in PHP

Using default parameters with functions is same as using it in C++. Only difference is in the function declaration. In C++, you must define default values from right end. 

For example :

// Valid in C++
int test( int i , long j = 10) {}   


// Invalid in C++, you must start providing the default value from right end
int test( int i = 10, long j ) {}   



But in php, the second statement above is a valid function declaration but you need to call the function as shown below:

// Function Definition
function test( int i = 10, long j ) {}

// Valid call
test(2,4); 

// Invalid, will give "Missing argument 2 for test()"
test(1); 


The calling rules are same for both php and c++ function calls.

Another example :


// Function Declaration
function test($a = 4, $b, $c = 10) {}  


// $c gets 10 from default parameters
test(8,9);           


// Invalid call as Argument 2 is missing
test(9);                

No comments: