Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}



}
like image 526
Brian Patterson Avatar asked Jan 31 '13 21:01

Brian Patterson


People also ask

Can you assign the default values to a function parameters in PHP?

PHP allows us to set default argument values for function parameters. If we do not pass any argument for a parameter with default value then PHP will use the default set value for this parameter in the function call.

What is the default value of a variable in PHP?

Uninitialized variables have a default value of their type depending on the context in which they are used - booleans default to false , integers and floats default to zero, strings (e.g. used in echo) are set as an empty string and arrays become to an empty array.

What is $params in PHP?

PHP Parameterized functions They are declared inside the brackets, after the function name. A parameter is a value you pass to a function or strategy. It can be a few value put away in a variable, or a literal value you pass on the fly.

Can you pass functions as parameters in php?

PHP Parameterized functions are the functions with parameters. You can pass any number of parameters inside a function. These passed parameters act as variables inside your function. They are specified inside the parentheses, after the function name.


1 Answers

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;
like image 172
cmbuckley Avatar answered Oct 22 '22 13:10

cmbuckley