Brian Patterson
Brian Patterson

Reputation: 1625

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

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

}



}

Upvotes: 11

Views: 4279

Answers (3)

cmbuckley
cmbuckley

Reputation: 42468

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;

Upvotes: 21

Victor Bocharsky
Victor Bocharsky

Reputation: 12306

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

Upvotes: 0

brianreavis
brianreavis

Reputation: 11546

"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

Upvotes: 5

Related Questions