PHP pass default argument to function PHP pass default argument to function php php

PHP pass default argument to function


This is not natively possible in PHP. There are workarounds like using arrays to pass all parameters instead of a row of arguments, but they have massive downsides.

The best manual workaround that I can think of is defining a constant with an arbitrary value that can't collide with a real value. For example, for a parameter that can never be -1:

define("DEFAULT_ARGUMENT", -1);

and test for that:

function($foo = DEFAULT_ARGUMENT, $bar = false){}


put them the other way round:

function($bar = false, $foo = 12345){}function(true);


The usual approach to this is that if (is_null($foo)) the function replaces it with the default. Use null, empty string, etc. to "skip" arguments. This is how most built-in PHP functions that need to skip arguments do it.

<?phpfunction($foo = null, $bar = false)    {    if (is_null($foo))        {        $foo = 12345;        }    }?>