PHP Using $this->variable as Class Method Parameter Default Value PHP Using $this->variable as Class Method Parameter Default Value php php

PHP Using $this->variable as Class Method Parameter Default Value


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;


"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


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