I have a class and in the constructor I determine the value of a property of the class; Why can't I use this class property as a default value in a method?
Or am I not using the proper property or property type?
class FooClass
{
public string $defenv = '';
public function __construct($theme = 'default')
{
//En el constructor determino el tipo de interface usada
$this->defenv = $this->IsCommandLineInterface() ? 'cli' : 'web';
}
private function IsCommandLineInterface()
{
return (php_sapi_name() === 'cli');
}
public function foo($env = $this->defenv){
echo $env;
}
}
Mistake
Fatal error: Constant expression contains invalid operations in
I find myself needing to make these changes to make it work (it's still inside the class):
public function foo($env = ''){
if ($env == '') {
$env = $this->defenv;
}
echo $env;
}
Note: I have previously instantiated the class and call it as follows:
$example = new FooClass();
$example->foo()
The particular case you want to solve can be achieved. But, generating the constant to be used by using the define() method that supports the use of functions that return some value as values to assign.
The solution could look like this:
In the documentation for in the Default Argument Values
PHP
section it says:One solution ( as @Triby commented ) is to use the null merge operator
Example: