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;
Sign up to request clarification or add additional context in comments.

3 Comments

You could use my tiny library ValueResolver to do it more compact
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!
Wow, looks like both Victor and I copied the OP and never noticed the mistake! Thanks, fixed :-)
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

Comments

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 Comments

Why would you add an entire 3rd party package just to do something as simple as $default = $default ?: $this->somevar;?
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
@harryg It also will be useful for automate some parts of framework with it

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.