Question

Is this legal?

<?php

function ftw($foo = 'pwnage', $nub = MENU_DEFAULT_VALUE, $odp = ODP_DEFAULT_VALUE) {
      //lots_of_awesome_code
}

?>

where MENU_DEFAULT_VALUE and ODP_DEFAULT_VALUE are constants defined previously in the file.

Was it helpful?

Solution

Yes, that is legal.

From the manual:

The default value must be a constant expression, not (for example) a variable, a class member or a function call.

Constants fit that bill perfectly.

OTHER TIPS

In an OOP context, you can also use a class member constant as a default method argument value.

class MyClass
{
    const A = 1;

    public function __construct($arg = self::A)
    {
        echo $arg;
    }
}

why don't you try ?

Still, just in case you can test right now, the following code :

define('MENU_DEFAULT_VALUE', 10);
define('ODP_DEFAULT_VALUE', 'hello');

function ftw($foo = 'pwnage', $nub = MENU_DEFAULT_VALUE, $odp = ODP_DEFAULT_VALUE) {
    var_dump($foo);
    var_dump($nub);
    var_dump($odp);
}

ftw();

gives this output :

string 'pwnage' (length=6)
int 10
string 'hello' (length=5)

So I'd say that, yes, it is valid :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top