Reputation: 122392
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.
Upvotes: 25
Views: 12340
Reputation: 14544
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;
}
}
Upvotes: 22
Reputation: 94147
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.
Upvotes: 34
Reputation: 400922
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 :-)
Upvotes: 9