arik
arik

Reputation: 29260

PHP pass default argument to function

I have a PHP function, like this:

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

What I want to do, is call this function with the default argument of $foo passed, but $bar set to true, like this (more or less)

function(DEFAULT_VALUE, true);

How do I do it? How do I pass an argument as a function's default value without knowing that value?

Thanks in advance!

Upvotes: 12

Views: 7872

Answers (5)

theHack
theHack

Reputation: 2014

i think, it's better sorted based on the argument that the most frequently changed, $bar for example, we put it first,

function foo( $bar = false, $foo = 12345){
// blah blah...
}

so when you want to pass $bar to true, and $foo to 12345, you do this,

foo(true);

Upvotes: -2

Pekka
Pekka

Reputation: 449415

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){}

Upvotes: 12

Tesserex
Tesserex

Reputation: 17314

PHP can't do exactly that, so you'll have to work around it. Since you already need the function in its current form, just define another:

function blah_foo($bar)
{
    blah(12345, $bar);
}

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

Upvotes: 3

Core Xii
Core Xii

Reputation: 6441

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.

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

Upvotes: 3

Freddie
Freddie

Reputation: 1707

put them the other way round:

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

function(true);

Upvotes: 3

Related Questions