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) {
}
}
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.
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With