11

Ok so this seems like a pretty dumb question but PHP Is telling me I can't do this, or rather my IDE...

In the below example its telling me I can't use $this->somevar as the default value for the method.

ie...

class something {

public somevar = 'someval';

private function somefunc($default = $this->somevar) {

}



}
1

3 Answers 3

21

I'm afraid your IDE is correct. This is because "the default value must be a constant expression, not (for example) a variable, a class member or a function call." — Function arguments

You'll need to do something like this:

class something {

    public $somevar = 'someval';

    private function somefunc($default = null) {
        if ($default === null) {
            $default = $this->somevar;
        }
    }
}

This can also be written using the ternary operator:

$default = $default ?: $this->somevar;
3
  • You could use my tiny library ValueResolver to do it more compact Jul 9, 2015 at 10:41
  • Tiny error public somevar = 'someval'; is missing the $ and should be public $somevar = 'someval'; I copied and pasted to just re-craft it and lost about 30 seconds flummoxed. Posted this here just in case another numbskull comes along!
    – BeNice
    Jul 24, 2019 at 12:56
  • Wow, looks like both Victor and I copied the OP and never noticed the mistake! Thanks, fixed :-)
    – cmbuckley
    Jul 25, 2019 at 9:40
5

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

http://php.net/manual/en/functions.arguments.php

0

You could use my tiny library ValueResolver in this case, for example:

class something {

    public somevar = 'someval';

    private function somefunc($default = null) {
        $default = ValueResolver::resolve($default, $this->somevar); // returns $this->somevar value if $default is empty
    }
}

and don't forget to use namespace use LapaLabs\ValueResolver\Resolver\ValueResolver;

There are also ability to typecasting, for example if your variable's value should be integer, so use this:

$id = ValueResolver::toInteger('6 apples', 1); // returns 6
$id = ValueResolver::toInteger('There are no apples', 1); // returns 1 (used default value)

Check the docs for more examples

3
  • Why would you add an entire 3rd party package just to do something as simple as $default = $default ?: $this->somevar;?
    – harryg
    Jul 9, 2015 at 10:50
  • There are few additional methods for typecasting it it. Also I plan to do this library more complex to avoid usage of isset function in code Jul 9, 2015 at 10:58
  • @harryg It also will be useful for automate some parts of framework with it Jul 9, 2015 at 11:02

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.