25

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.

1
  • 2
    yeah, but I was having problems in a function that uses this and I thought maybe it was technically possible but against best practices. Commented Aug 5, 2009 at 4:27

3 Answers 3

34

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Any reason/documentation for not being able to refer to the constant using static but just via self, when setting defaults for a class method argument?
@Kamafeather static is subject to late static bindings, making it inconstant.
22

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;
    }
}

Comments

9

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 :-)

1 Comment

In the context of a class method I found out that is not possible to refer to the constant via static, but just using self; this myMethod($arg1 = static::MY_CONST) won't work. Do you know any valid explanation for this different behaviour?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.